The Python list can be converted into string by using the following methods. Let’s understand the following methods.
Method - 1
The given string iterates using for loop and adds its element to string variable.
Example -
# List is converting into string
def convertList(list1):
str = '' # initializing the empty string
for i in list1: #Iterating and adding the list element to the str variable
str += i
return str
list1 = ["Hello"," My", " Name is ","Devansh"] #passing string
print(convertList(list1)) # Printin the converted string value
Output:
Hello My Name is Devansh
Method -2 Using .join() method
We can also use the .join() method to convert the list into string.
Example - 2
# List is converting into string
def convertList(list1):
str = '' # initializing the empty string
return (str.join()) # return string
list1 = ["Hello"," My", " Name is ","Devansh"] #passing string
print(convertList(list1)) # Printin the converted string value
Output:
Hello My Name is Devansh
The above method is not recommended when a list contains both string and integer as its element. Use the adding element to string variable in such scenario.
Method - 3
Using list comprehension
# Converting list into string using list comprehension
list1 = ["Peter", 18, "John", 20, "Dhanuska",26]
convertList = ' '.join([str(e) for e in list1]) #List comprehension
print(convertList)
Output:
Peter 18 John 20 Dhanuska 26
Method - 4
Using map()
# Converting list into string using list comprehension
list1 = ["Peter", 18, "John", 20, "Dhanuska",26]
convertList = ' '.join(map(str,list1)) # using map funtion
print(convertList)
Output:
Peter 18 John 20 Dhanuska 26