Register Login

How to Convert List to String in Python with Examples

Updated May 10, 2023

In today's technical fields, almost every programmer finds Python the most efficient and easy toolkit for creating user-friendly programs. It is one of the most prevalent programming languages, which provides various tools, packages, methods, etc.; that help programmers to process data in real-time and interact with end-Programmers smoothly.

Python also renders data types, like list, dictionary, tuple, and set that store data sets in an ordered or unordered collection. In this article, you will understand how to convert a list into a string using various methods and techniques.

What is a list in Python?

Programmers can use a list to store multiple elements, an ordered collection of data sets where these elements can be of the same or different data types. Lists are one of the data types that hold a collection of data with special applications and advantages.

Syntax:

the_list = [1, "A", "XYZ", 4.5]

Different programming languages have different syntaxes that Programmers can use to create a list. The list is mutable and allows duplicate items. Programmers can generate two types of lists, i.e., homogenous and heterogeneous. Homogenous list stores only one type of data or elements, whereas a Heterogeneous list stores multiple data type elements.

  • Homogenous: the_list = [1, 2, 3, 4]
  • Heterogenous: the_list = [1, "A", "XYZ", 334.64]

What is a string in Python?

Another data type, string, is a collection of a sequence of characters like letters, numbers, punctuations, and many other symbols, within the single quotation or double quotation marks. Strings are immutable, which means Programmers cannot change the value of the string once they create strings. Programmers use the print () function to display a string.

Syntax:

print("This is Python string.")

Why do programmers convert lists into strings in Python?

There are various reasons for the conversion of lists into strings in Python in different circumstances discussed below:

  • Effective Transmission and Data Storage: When it comes to storing data and transmission, Programmers should use strings rather than using lists. It is because converting the data from a list to a Python string for proper and better data transmission over the network.
  • Compatibility: Often Programmers need to use APIs and libraries where they pass data in string format. In such circumstances, Programmers convert the list into a string before passing the data into the API or library.
  • Comparison: While comparing two lists, converting both lists into strings and then comparing the strings; is more efficient and advantageous.

Following are some methods that allow Programmers to change a list into a string in Python:

  1. join()
  2. map()
  3. list comprehension
  4. Traversal of list
  5. Iterating through the list
  6. in operator
  7. Enumerate
  8. functools.reduce
  9. recursion
  10. str.format
  11. Mixed string

Method 1: Using the join() method

It is one of the most widely used and simplest methods Programmers can use to convert the list into a string. It is a built-in method that takes all the elements into an iterable and then joins these iterable's elements into a single string.

Syntax:

string.join(iterable)

Parameters used:

It takes only one parameter, i.e., iterable, that specifies all the iterable elements returned as strings.

Code Snippet:

a=['This','is','an','example','of','join()' 'function', 2, 8.9]
demo=' '.join(map(str, a))
print(demo)

Output:

Convert List to String in Python Using the join() method

Explanation:

Here, we used the join() method that converts the list of individual strings into a single string. In the join() methods, Programmers can only use a homogenous list where all the elements have the same data types.

Also, Programmers must remember that they can use the join() method only if they list that contains only string as its elements.

Method 2: Using the map() function

Programmers can use the map() function, an iterator that returns a map object. It loops over every element of the iterable and applies the transformation to the values.

Syntax:

map(function, iteration)

Parameters used:

It takes two parameters, where the first parameter specifies the data types into a string data type. And the second data type defines the mapping of the iterable element.

Programmers can use the map() function in two specific cases to convert a list to a string, i.e., when the list contains only numbers or is a heterogeneous list.

Code Snippet:

a = ['This', 'is', 'an', 'example', 'of', 'map()', 'function', 2, 8.9]
demo = ' '.join(map(str, a))
print(demo)

Output:

Explanation:

In the above example, we used the map() function to convert the list into a string and, lastly, added the join() function to merge all the elements returned by the str() function.

Method 3: Using the list comprehension technique

In Python, list comprehension creates a list of items from the existing list. It then uses the for loop to traverse the iterable elements in an element-wise format. In the following example, we will see how it works:

Code Snippet:

a = ['This', 'is', 'an', 'example', 'of', 'comprehension' 'technique', 2, 8.9]
demo = ' '.join([str(elem) for elem in a])
print(demo)

Output:

Explanation:

In this example, we used the list comprehension method that traverses list items one after another. Then, we used the join() method that concatenates the elements in the list into a new string and returns this Python string in the output console.

Method 4: Using the traversal of list technique

The Python list is a container data structure where Programmers can access the elements in the list one by one and get the elements by its index. They can traverse using the for loop and range methods and here we will show how to use the traversing method to convert the list into a string:

Code Snippet:

a = ['This', 'is', 'an', 'example', 'of', 'traversal', 'technique']
b = ''
for i in a:
    b += '  ' +i
print (b)

Output:

Explanation:

In this code snippet, first, we initialized a list "a" that we will convert into a string. Then we initialized an empty string that will store the elements.

After that, we used the for loop to traverse each element in the list, and for each index, the for loop will add the element to the initialized string. Lastly, we used the print() function to print the string in the output console.

Note: Give a space between the single quotations used in the for loop under the variable "b" so that the loop returns a string with blank space between each word in the output console.

Method 5: Iterating through the list to convert the list into a string

In this method, we will use two techniques to convert the list into a string in Python, and these are as follows:

Example 1

Code Snippet:

a = ['This', 'is', 'an', 'example', 'of', 'Iterating', 'list']
b = " "
for i in a:
    b += i + ' '
print(b)

Output:

Explanation:

In this example, we assigned a list, traversed each element, and added the elements into an empty string using for loop.

Example 2: In the second example of iteration, we will use a Python function and convert the list into a string.

Code Snippet:

def sample(s):
	demo = " "
	for i in a:
		demo += i + ' '
	return demo
a = ['This', 'is', 'an', 'example', 'of', 'map()' 'function']
print(sample(a))

Output:

Explanation:

Here, we first declared a function named "sample," inside the function, we traversed each element of the list and kept inserting new elements for every index within the empty string using for loop. It will iterate through the list and thus generate a Python string with all the elements of the list.

Method 6: Using the in operator

It is another way to convert a list into a string in Python. The in operator allows Programmers to check in an element exists within the collection of multiple elements, which can be a string, list, set, tuple, etc.

Code Snippet:

a= ['This', 'is', 'an', 'example', 'of', 'in', 'operator']
for i in a:
print(i, end = " ")

Output:

Explanation:

In this example, we used the for loop with the in operator to convert the list into a string.

Method 7: Using Enumerate function

The enumerate function is a built-in function that allows Programmers to keep a count of the number of loops or iterations in a loop.

Syntax:

enumerate (iterable, start=0)

Parameters used:

The first parameter, i.e., the iterable parameter specifies the element to be iterable, and the second parameter, i.e., a start parameter holds a number that starts a number of the enumerated element.

Example 1

Code Snippet:

a = ['We', 'are', 'using', 'Python']
b = ' '
for i, fruit in enumerate(a):
 b += str(i) + ' ' + fruit + ' '
 b = b[:-1]
print(b)

Output:

Explanation:

In this code snippet, we used the enumerate function that converts the declared list into a string, and Programmers can iterate over the given list and fetch the index of each element. Lastly, we used the string concatenation technique to generate the final string.

Example 2

Code Snippet:

a = ['We', 'are', 'using', 'Python', 'to', 'convert', 'list', 'into', 'string.']
b = ' '.join([str(elem) for i,elem in enumerate(a)])
print(b)

Output:

Method 8: Using the functools.reduce function

The functools.reduce function is a function in Python under the functools modules that returns a single item as the output, which is the output of the entire iterable where Programmers will obtain a single integer that gets reduced in string or boolean.

Code Snippet:

from functools import reduce
a = ['We', 'are', 'using', 'Python', 'to', 'convert', 'list', 'into', 'string.']
b = reduce(lambda x, y: x + ' ' + y, a)
print(b)

Output:

Explanation:

We used the reduce() function of the functools module with the lambda function to convert the list into a string after concatenating the elements of the list into a string. We used the reduce() function that applies a function to the iterable element to reduce it into a single element.

Method 9: Using the recursion method

Code Snippet:

def demo(s, a, w):
    if s == len(a):return w 
    w += str(a[s])+' ' 
    return demo(s+1, a, w) 
a = ['We', 'are', 'using', 'Python.'] 
print(demo(0, a,''))

Output:

Explanation:

First, we have defined the function "demo." Inside that function, we declared a list with only string values. We recursively called the "demo" function that added each element from the list into the new string and finally print the string to the console.

Method 10: Using the str.format method

One of the efficient ways to convert a list into a string is to use an str.format method that allows Programmers to format strings using placeholders. Follow the code snippet and its relative explanation to understand how it works:

Code Snippet:

a = ['We', 'are', 'using', 'Python', 'to', 'convert', 'list', 'into', 'string.']
b = ''
for demo in a:
    b += '{} '.format(demo)
print(b)

Output:

Explanation:

In the above example of the str.format method, we initialized a list with string values as the elements. Then we again declared a variable with a blank string that will return the new string elements in the output console. Lastly, we used the {} placeholder to add each item of the given list into a string.

Method 11: Using Mixed string representation with rounding

It is the last technique of this article to convert a list into a string. When Programmers need to represent the Python list in different formats apply distinct techniques to accomplish the condition. In this example, we will see how to mix two methods to achieve what we need in this article:

Code Snippet:

a = ['I', 'have', 'bought', 2, 'dresses', 'and', 1, 'shoe.']
b = ' '.join(['{:.2f}'.format(i) if type(i) == float else str(i) for i in a])
print(b)

Output:

Explanation:

Here, we have combined list comprehension and string formatting to convert the Python list into a string. Again, the join() method joins each element of the list and returns a new string, and the format() method formats the specified elements and inserts these values within the placeholder of the string.

Conclusion:

Finally, we conclude by understanding all the techniques programmers can use to convert a list into a string. In this article, we found eleven methods and tools of Python that allow programmers to manipulate a data type into another as per their choice. This article also discussed the relevant application and grounds why programmers need this conversion with examples and explanations.


×