Convert a List into a String in Python
In this tutorial, we will learn how to convert a list into a string in Python.
A list is a collection of elements that are mutable and ordered. ( Learn: What are the Mutable and Immutable objects in Python? )
The termĀ mutable means that the elements may be modified.
There are different methods to convert list into a string. Let’s see one by one.
Creating a List: Convert a List into a String in Python
l = ["pavan" , "jagan" , "venkat" , 1, 2, 3.9] print (l) print (type(l))
Output : ['pavan', 'jagan', 'venkat', 1, 2, 3.9] <class 'list'>
Method 1: Iterative
Using the Iterative method to convert every element in the list to add into a string.
def convert_to_string (l): # naive method string = "" for i in l: string += i return string l = ["pavan" , "jagan" , "venkat"] print (convert_to_string(l))
Output : pavanjaganvenkat
Method 2: list into a string
Certainly, the conversion could be done in a single line.
Therefore, List Comprehension technique with the ” .join ” function can be used to convert a list into a string.
l = ["Achievers", "pavan" , "jagan" , "venkat" , "bhanu"] con_str = ' ' .join( [ str(i) for i in l] ) # using .join and list comprehension print (con_str)
Output : Achievers pavan jagan venkat bhanu
Method 3: list to string in Python
In contrast, to the above methods, a higher-order function can be used likeĀ map.
Probably, the below example is likely to clear the concept.
l = ["bhanu" , "surya" , "bolla" , "sairam"] # a list con_str = ' ' .join (map(str,l)) # using .join and map( function , sequence) print (con_str)
Output : bhanu surya bolla sairam
Concluding the topic, even if the list is most flexible there would be some requirements to convert them.
Moreover, the above methods help to convert them and use other sequences also.
Leave a Reply