Python program to convert a list to string
There are various situations we might encounter when a list is given and we convert it to a string. For example, conversion to string from the list of strings or the list of integers or mixed data types.
Input: ['Geeks', 'for', 'Geeks'] Output: Geeks for Geeks Input: ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] Output: I want 4 apples and 18 bananas
Let’s see various ways we can convert the list to string.
Method#1: The first method is to assign a list and traverse each element using for loop and adding it to an empty string.
Python3
s = [ 'Geeks' , 'for' , 'Geeks' ] str1 = "" # traverse in the string for i in s: str1 + = i print (str1) |
Output:
GeeksforGeeks
type(str1) str
Method #2: The Second method used here is using a function that traverse each element of the list using for loop and keep adding the element for every index in some empty string.
Python3
# Python program to convert a list to string # Function to convert def listToString(s): # initialize an empty string str1 = "" # traverse in the string for ele in s: str1 + = ele # return string return str1 # Driver code s = [ 'Geeks' , 'for' , 'Geeks' ] print (listToString(s)) |
GeeksforGeeks
Method #3: Using .join() method
Python3
# Python program to convert a list # to string using join() function # Function to convert def listToString(s): # initialize an empty string str1 = " " # return string return (str1.join(s)) # Driver code s = [ 'Geeks' , 'for' , 'Geeks' ] print (listToString(s)) |
Geeks for Geeks
But what if the list contains both string and integer as its element. In those cases, above code won’t work. We need to convert it to string while adding to string.
Method #4: Using list comprehension
Python3
# Python program to convert a list # to string using list comprehension s = [ 'I' , 'want' , 4 , 'apples' , 'and' , 18 , 'bananas' ] # using list comprehension listToStr = ' ' .join([ str (elem) for elem in s]) print (listToStr) |
I want 4 apples and 18 bananas
Method #5: Using map() Use map() method for mapping str (for converting elements in list to string) with given iterator, the list.
Python3
# Python program to convert a list # to string using list comprehension s = [ 'I' , 'want' , 4 , 'apples' , 'and' , 18 , 'bananas' ] # using list comprehension listToStr = ' ' .join( map ( str , s)) print (listToStr) |
I want 4 apples and 18 bananas