In this post, we will learn how to convert list to string in python with very simple explanation and example.

There are four different ways to convert a list into a string. Let’s explore each of these one by one.

Using join() Method

The join() method helps us to join the elements of the list into a string with the help of a separator.

my_list = ["a","b","c"]
string = " ".join(my_list)

print(string) # Output: a b c
print(type(string)) # Output: <class 'str'>

In this example, all the elements of the list are strings. However, consider a list containing a mix of elements, including both strings and numbers. In that case, the join() method will not work because, to convert a list into a string, you must first convert all the elements of the list into strings. Then, you can use the join() method to combine them into a single string.

If you have a mixed list then you can use the map() function along with the join() method.

Using map() & join()

We will use the map() function to convert all the elements of the list into a string and after that, we will use the join() method to combine them into a single string.

Let’s see it with the help of example:

my_list = ["a","b","c",1]
string = " ".join(map(str,my_list))

print(string) # Output: a b c 1
print(type(string)) # Output: <class 'str'>

We can also achieve the same thing using for-loop.

Using for loop

my_list = ["a","b","c",2]
string = ""

for s in my_list:
    string = string + str(s) +" "

print(string) # Output: a b c 2 
print(type(string)) # Output: <class 'str'>

If you want your code to be shorter and easier to understand, you can use list comprehension instead of a for-loop.

Using List Comprehension

my_list = ["a","b","c",3]
string = " ".join([str(s) for s in my_list])

print(string) # Output: a b c 3 
print(type(string)) # Output: <class 'str'>

This is all the four ways to convert the list into a string, hope you will understand it well – thank you

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment