Skip to main content
Convert Python List to String

Python List to String

This python tutorial help to convert a python list into a string. We’ll learn different ways to convert list items into the string.

There are two types of lists. heterogeneous or homogeneous A list is heterogeneous if it stores different data types at the same time, and homogeneous if it stores the same date style items at the same time.

What Is a List in Python?

In Python, a list is an ordered sequence that can hold a number of object types like integers, characters, and floats. In various computer languages, a list is equivalent to an array. Square brackets are used to denote it, and a comma(,) is used to divide two objects in the list.

The index in the list can be used to find a specific item in the list. The indexing of the list’s elements begins at 0.

What Is a String in Python?

In Python, a string is an ordered collection of characters. The difference between a list and a string should be recognised. A list is an ordered sequence of object types, whereas a string is an ordered sequence of characters.

How to Convert a List to String in Python

Let’s start to convert a list of items into the string using python 3.

Option 1: List Comprehension

You can use the join() method with the List comprehension. List comprehension will help you in creating a list of elements from the input list.

The join() method concatenates the list’s elements into a new string and returns it as output, while the list comprehension traverses the elements one by one.

s = ['Python', 'PHP', 'JavaScript'] 
# using list comprehension 
listToStr = ' '.join([str(element) for element in s])
print(listToStr)

Output:

Python PHP JavaScript

Option 2: join() Method

The Join() method is used to concatenate all these elements and return the string. If the list contains integer members, this function will fail, and the result will be a TypeError Exception.

s = ['Python', 'PHP', 'JavaScript'] 
string = " "

string= string.join(s) 
print(string)

Output:

Python PHP JavaScript

Option 3: Using For Loop

The python loop method is used to convert a list into a string. The for loop will iterate every index of the input list one by one and add it to the empty string.

str = ""
s = ['Python', 'PHP', 'JavaScript'] 
for element in s:
    str += " " +element 
print(str)

Output:

Python PHP JavaScript

You can also checkout other python tutorials:

Option 4: Using map() Method

The map function is also used to convert lists into string. The map() function accepts the iterable objects such as tuples, lists, or strings. It’s used to map the elements of iterable objects using the specified function.

s = ['Python', 'PHP', 'JavaScript']

listToStr = ' '.join(map(str, s)) 
print(listToStr)

Output:

Python PHP JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *