- Program to convert a list to string in Python
- Using join[] method
- Using List Comprehension
- Iterating using for loop
- Using map[] method
There are various scenarios where you would need to convert a list in python to a string.We will look into each of these scenarios in depth.
Lists are one of the four built-in data types in Python. A list is a data type in Python and is a collection of items that contain elements of multiple data types.
The elements of the list can be converted to a string by either of the following methods:
- Using join[] method
- Using List Comprehension
- Iterating using for loop
- Using map[] method
Program to convert a list to string in Python
Using join[] method
Thejoin[] method takes all items in aniterableand joins each element of aniterable[such as list,string, and tuple] into one concatenatedstring.
If the iterable contains any non-string values, it raises a TypeError exception.
Syntax:string.join[iterable]
Using List Comprehension
List comprehensionsprovide a concise way to create lists and will traverse the elements, and with the join[] method, we can concatenate the elements of the list in python into a new string.
# Python convert list to string using list comprehension s = ['Its', 4, 'am', 'in', 'america'] # using list comprehension listToStr = ' '.join[[str[elem] for elem in s]] print[listToStr] # Output Its 4 am in americaIterating using for loop
Iterating using for loop is a simple technique used in many programming languages to iterate over the elements in the list and concatenate each item to a new empty string.
# 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 # Main code str= ['Life', 'is', 'Beautiful'] print[listToString[str]]# Output LifeisBeautifulUsing map[] method
Pythons map[] is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop.
# Python program to convert a list to string using list comprehension s= ['Life', 'is', 'Beautiful'] # using list comprehension listToStr = ' '.join[map[str, s]] print[listToStr] # Output Life is Beautiful