Convert a list to string in Python

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

The join() method takes all items in an iterable and joins each element of an iterable (such as list, string, and tuple) into one concatenated string.

If the iterable contains any non-string values, it raises a TypeError exception.

Syntax: string.join(iterable)

# Python convert list to string	using join() method

# Function to convert  
def listToString(items): 
    # initialize an empty string
   str1 = "" 
   return (str1.join(s))

# Main code  
s= ['Life', 'is', 'Beautiful']
# Output LifeisBeautiful

Using List Comprehension

List comprehensions provide 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])

# Output Its 4 am in america

Iterating 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']
# Output LifeisBeautiful

Using map() method

Python’s 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))
# Output Life is Beautiful
Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like