Convert a List into a String in Python
In this tutorial, we will learn how to convert a list into a string in Python. The string we are going to create will contain all the items of the list. We can also add a separator like a space or comma after each item.
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 a Python 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 of code. Therefore, the list comprehension technique with the .join
function can be used to convert a list into a string like you can see in the example below:
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
As you can see in this example, we have used the whitespace as the separator for list items ' ' .join( [ str(i) for i in l] )
. In this way, each item in the string is separated by whitespace.
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.
Leave a Reply