Python Convert All Elements Of List To String

If you use list frequently in your python code, then you may have come across a situation, where you need to convert all elements of List to string. In this post, we will see two approaches to do that. First, we will convert the entire list to a string so that it will become a line. Second, we will convert all elements to strings keeping the list as it is.

Automate Boring Stuff With Python

#Scenario 1


Input: list1=["I","am","a","list"]

Output: I am a list

#Scenario 2


Input: list2=["I","am","a","list2",1,2,3]

Output: ["I","am","a","list2","1","2","3"]

Convert Entire List To A Line In Python

We can convert an entire list to a line or string by using the Join operator. The join operator is an inbuilt python function, which joins a list with a separator. A separator can be anything, but the most common are space, comma, colon, and even a special character. We are going to use a space separator to convert the list into a single string or line.

#Create a List
list1=["I","am","a","list1"]
#Convert list using join operator
line=" ".join(list1)
#Print The output
print(line)
#Output
"I am a list1"

Python Convert All Elements Of List To String

Now you may notice that the second list contains strings and integers. Hence, and it is a list with mixed data types, and if use joins operator directly it will give a TypeError as below.

TypeError: sequence item 4: expected str instance, int found

In order to resolve this first, you need to convert all elements to string keeping the list as it is and then use the join operator. We will use the map function and the join operator to solve it.

>>> list2=["I","am","a","list2",1,2,3]
>>> newlist=list(map(str,list2))
>>> print(newlist)
['I', 'am', 'a', 'list2', '1', '2', '3']
>>> opt=" ".join(newlist)
>>> print(opt)
I am a list2 1 2 3
>>> 

Conclusion

You can the same code to convert all elements of the list to int or float. However, you must check if the list’s elements are of correct data types to avoid any TypeError.

As a part of storage automation, I have written many python scripts and the list is my favorite. A python list can be useful in storing multiple variables which can be processed in many ways. I strongly suggest playing around with the python list, especially using it with for loop.

I hope, this post was helpful, Check out our YouTube channel for a basic tutorial on python and storage admin videos.