How to Convert a List to a String in Python

Converting a list into strings is helpful in many situations like doing data manipulations, storing or sending the data, and more. Having data in string format makes it more human-readable. This article discusses the methods to convert a list into Python while illustrating each method with an example.

Significance of List to String Conversion

Converting a list to a string is helpful in different scenarios like

  • The data should be formatted to a string which makes it easier to manipulate.
  • When storing the data in a database or if the data is to be sent, it is better to convert it to a string.
  • When comparing two lists, converting them to a string makes it a lot more convenient.
  • Certain libraries require parameters to be passed as strings.

How to Convert a List to a String in Python?

A list contains items in an ordered form. The elements are split by the commas inside the square brackets. The list can store any data type and it is not bound to have elements of a single data type. A collection of characters that are written inside inverted commas and square brackets is a string.

Various methods to convert a list to a string in Python are:

  1. Using join() function
  2. Using for loop
  3. Using map() and join() function
  4. Using a list comprehension
  5. Using enumerate() function
  6. Using recursion
  7. Using functools.reduce
  8. Using the str.format method
  9. Using mixed string representation with rounding

Let us discuss each method in detail.

Method 1: Using join() 

Using the join() method, each item in the list will be traversed and integrated into an empty string already defined before. This method puts together the elements with the final output. The method does not work if integer values are provided in the sample_list. Here is the code for converting the list to a string using Python:

def listToStr(lst):
    str = " "
    return (str.join(lst))
sample_list = ['Harry', 'Avril', 'Hailee']
print(listToStr(sample_list))

In the above code,

  • A function listToStr is defined that takes the parameter lst.
  • An empty string is initialized in str
  • The join function joins together the str element with the elements of the list.
  • The function is called on the sample_list.

Output

The following output displays how a list can be converted to a string using the join() method:

Method 2: Using a For loop

A list can be converted to a string in Python using a for loop. An empty list is defined and each element in the sample list is iterated and integrated into an empty string. The following code shows how to convert a list to a string in Python using a for loop:

def listToStr(lst):
    str = " " 
    for i in lst: 
        str += i 
    return str
sample_list = ['What ', 'Defines ', 'Us ']
print(listToStr(sample_list))

In the above code,

  • A function listToStr is defined that takes the parameter lst.
  • An empty string str is defined.
  • The function iterates through each element in the provided list and adds it to the empty string.
  • A sample list is defined and the function is called upon it.

Output

The following output displays how to convert a list to a string using the for loop:

Method 3: Using Map and join the Function 

The map() function takes objects that can be repeated like a list or a tuple as a parameter and gives back an iterator by applying a specific functionality to each element in the input. Here is the code that shows how you can convert a list to a string using the map() function in Python:

sample_list = ['I ', 'Code in ', 'Python ']
listToStr = ' '.join(map(str, sample_list))
print(listToStr)

In the above code,

  • A sample_list is defined.
  • The map(str, sample_list) function ensures that the element inside the sample_list is a string. The join() function joins the resulting values with a space.
  • The resulting string values are stored in listToStr which is then printed.

Output

The following output shows how the list can be converted to a string using the map() function:

Method 4: Using a List Comprehension

The join() method does not allow integers to be a part of the result but using a list comprehension, integers can also be added. List comprehension enables you to create a list of elements from an input list and a loop is created to transverse each element inside the sample list. The join() method joins the elements in an empty string. The following code shows how a list can be converted to a string in Python using list comprehension:

sample_list = ['Food ', 'for ', 'thought ']
listToStr = ' '.join([str(i) for i in sample_list])
print(listToStr)

In the above code,

  • A sample list is defined
  • Each element in the input list is converted to a string.
  • The transverse elements are then joined together with a space using the join() function.
  • The result is stored to listToStr which is then printed.

Output 

The following output displays how a list can be converted to a string using list comprehension:

Method 5: Using the enumerate() Function

The enumerate function enables each element to be iterated through while getting the information about its index value. The following code shows how a list can be converted to a string in Python using the enumerate function:

sample_list = [15, 'Nov ', 'is my ', 'birthday. ']
listToStr = ' '.join([str(i) for i, i in enumerate(sample_list)])
print(listToStr)

In the above code,

  • A sample list is defined.
  • The elements of the sample_list are joined with the spaces after they have been converted into strings and the enumerate function is called on each element of the sample list
  • The result is stored in the variable listToStr and then printed.

Output

The following output displays how a list can be converted to a string in Python using the enumerate function:

Method 6: Using Recursion

Using the recursion, a list can be converted into a string value which is then concatenated. It initiates from the initial value, joins together the present element to the words, and continues until it reaches the end value. The following code shows how recursion can be used to convert a list into a string using Python:

def listToStr(initial, sample_list, word)    if initial == len(sample_list):
        return word 
    word += str(sample_list[initial])+' '
    return listToStr(initial+1, sample_list, word)
sample_list = ['I', 'like to', 'code!']
print(listToStr(0, sample_list, ''))

In the above code,

  • A function listToStr is defined which takes “initial”, “sample_list”, and “word” as parameter values.
  • If the initial is equal to the length of the sample_list. It returns the “word”. If it is not equal, the present value from the sample list will be converted to the string value and stored in a “word” with a space.
  • The function calls itself recursively while incrementing the initial value.
  • When the initial becomes equal to the length of the sample list, the function returns the concatenated words.
  • The function is then called with an initial index of 0, an empty string, and the sample list. The resulting values are printed.

Output

The following output displays how a list can be converted to a string in Python using recursion:

Method 7: Using String functools.reduce

The functions module in Python provides a reduce() function that is applied to a specific function passed in the argument to all the items in the sequence and then gives back a single value. The following code shows how functools.reduce can be used to convert a list to a string:

from functools import reduce
sample_list= ['I', 'want', 2, 'slices', 'of', 'cheesecake']
listToStr = reduce(lambda x, y : x+ " " +str(y), sample_list)
print(listToStr)

In the above code,

  • The reduce method is imported from the functools module.
  • A sample list contains variables of different data types.
  • The reduce function with a Lambda function concatenates the elements inside the sample list. The elements will be contained inside a string with spaces in between them.
  • The string containing the elements of the list will be printed.

Output

The following output displays how a list can be converted to a string in Python using functools.reduce() method:

Method 8: Using the str.format

The str.format method was introduced to handle the complicated string formatting. Here is a code that uses the str.format does the conversion:

sample_list = ['Coding’, 'for', 'nerds']
op_str = "{} {} {}".format(*sample_list)
print(op_str)

In the above code,

  • A sample list is defined.
  • *sample_list” unpacks the elements inside the sample list and sends them as arguments to format().
  • {} acts as placeholders where the string values will be added. The resulting string is stored in the variable op_str which represents the output string.
  • The resulting string is then printed.

Output

The following output displays how a list can be converted to a string in Python using the str.format method:

Method 9: Using Mixed String Representation With Rounding 

There might be situations where elements need to be represented in various ways like rounding the numerical data to a specific number of decimal places. The string element remains as it is. This can be done using string formatting and list comprehension. The following code shows how a list can be converted to a string using the mixed string representation with rounding:

sample_list= ['Python', 'Java', 'PHP',.29]
sample_list =', '.join(['{:.2f}'.format(i) if type(i) == float else str(i) for i in sample_list])
print(sample_list)

In the above code,

  • A sample list is defined
  • If the element is a floating point number, it is formatted to display two decimal places.
  • If the element is not a floating point number, it gets converted to the string.
  • The formatted string elements are then joined together with “, “ using the join() function that adds space and comma to separate the string values.
  • The sample list is then printed.

Output

The following output displays how using mixed string representation with rounding can convert the list to string in Python:

Conclusion

Various functions in Python like join(), map(), enumerate(), str.format, functions.reduce() and more can be used to convert a list to a string. Converting a list to a string makes it human-readable and helps in convenient data storage and transformation. In this article, different methods to convert a list into a string were discussed, each method was illustrated with an example while highlighting the importance of converting a list value into a string.