Python lists and strings are similar in many ways but they are not the same. A list in python can hold any type of data in a single variable while a string can hold a set of characters.
If you regularly program using Python language then you might face a situation where you need to convert a list to a string. The examples of conversion of a list to a string are given below.
Example 1–
Input: ['Python', 'is', 'a', 'programming', 'language']
Output: Python is a programming language
Example 2–
Input: ['There', 'are', 10, 'apples', 'and', 15, 'mangoes','in', 'basket']
Output: There are 10 apples and 15 mangoes in basket
In this article, you will see different methods to change a python list to a string.
Method 1: Iterating through the list
The first way is to iterate through the list and keep adding its elements to an empty string.
For example –
# Python program to convert a list to string
# Function to convert a list to string
def listToString(list1):
str1 = ""
for i in list1:
str1 += i
return str1
list1 = ['Python ', 'is ', 'a ', 'programming ', 'language']
print(listToString(list1))
When you execute this you will see the given output.
Method 2: Using join() method
The join()
method in Python takes all items in an iterable and joins them into one string. This method only takes a string as an argument so before using any other data type you need to convert it into a string. Now see the given Python code.
# Python program to convert a list to string using join() function
# Function to convert list to string
def listToString(list1):
# initializing an empty string
str1 = " "
return (str1.join(str(i) for i in list1))
list1 = ['There', 'are', 10, 'apples', 'and', 15, 'mangoes','in', 'basket']
print(listToString(list1))
This will produce the given output.
Method 3: Using list comprehension
We can make the code of method 2 shorter by using list comprehension. You can see the example which is given below.
# Python program to convert a list to string using list comprehension
list1 = ['There', 'are', 10, 'apples', 'and', 15, 'mangoes','in', 'basket']
str1= ' '.join(str(i) for i in list1)
print(str1)
After executing this code you will see the following output.
Method 4: Using map() function
The map() function in Python applies a function to each element of an iterable. This function takes two arguments first is function and the second is iterable and returns a map object.
# Python program to convert a list to string using map() function
list1 = ['There', 'are', 10, 'apples', 'and', 15, 'mangoes','in', 'basket']
# using map() function
str1 = ' '.join(map(str, list1))
print(str1)
On executing this code it will produce the given output.
Conclusion
I hope you understand how to convert a python list to a string. If you have a query or feedback then write us in the comments below.