Skip to content

6 Ways to Convert a Python List to a String

Learn How to Convert a List to String in Python Cover Image

In this tutorial, you’ll learn how to use Python to convert (or join) a list to a string. Using Python to convert a list to a string is a very common task you’ll encounter. There are many different ways in which you can tackle this problem and you’ll learn the pros and cons of each of these approaches.

By the end of this tutorial, you’ll have learned:

  • How to use the .join() method to convert a Python list to a string
  • How to use the map() function to convert a Python list to a string
  • How to work with heterogenous lists when converting a list to a string
  • How to use for loops and list comprehensions to convert a Python list to a string
  • What method is the fastest when joining a list to a string

A Brief Refresher on Python Lists and Strings

Python lists are container data types that have a number of important attributes. Python lists are:

  1. Ordered, meaning that items maintain their order
  2. Indexable, meaning that items can be selected based on their position
  3. Mutable, meaning that we can modify lists
  4. Heterogenous, meaning that they can contain different types of objects (more on that shortly!)

Python lists are created by placing items into square brackets, separated by commas. Let’s take a look at how we can create a list:

# Creating a Sample List
a_list = ['Welcome', 'to', 'datagy.io']

In the code block above, we created a sample list that contains strings.

Python strings, on the other hand, are created using single, double, or triple quotes. Unlike Python lists, strings are immutable. However, they are ordered and indexable!

Let’s create a sample string in Python:

# Creating a Sample String
a_string = 'Welcome to datagy.io'

We can see that the list and the string contain the same set of English words. In this tutorial, you’ll learn how to convert the list of values into a broader string.

Using .join() to Convert a List to a String in Python

Python strings have many methods that can be applied to them. One of these methods is the .join() method, which allows you to use a string as a concatenation character to join a list of values.

The string to which we apply the .join() method represents the character (or characters) that will exist between each item in a list.

Let’s see how we can use Python’s .join() method to convert a list to a string:

# Using .join() to Convert a List to a String
a_list = ['Welcome', 'to', 'datagy.io']

a_string = ''.join(a_list)
print(a_string)

# Returns: Welcometodatagy.io

Let’s break down what we did in the code above:

  1. We declared our list of strings, a_list
  2. We then created a new variable a_string, which is the result of applying the .join() method to an empty string '' and passing in our list of values

We can see that this returned the concatenated string without any spaces in between!

If we wanted to separate the strings using a character, such as a space, we can simply apply the .join() method to a string containing that character!

# Using .join() to Convert a List to a String
a_list = ['Welcome', 'to', 'datagy.io']

a_string = ' '.join(a_list)
print(a_string)

# Returns: Welcome to datagy.io

In the code block above, we modified the string we’re applying the method to from an empty string to one that contains only a space, ' ' .

Problems with Using .join() To Convert a List to a String in Python

The .join() method expects that all elements in the list are strings. If any of the elements isn’t a string, the method will raise a TypeError, alerting the user that a string was expected.

Let’s see what this looks like:

# Raising a Type Error When Using the .join() Method
a_list = ['Welcome', 'to', 'datagy.io', 1]

a_string = ' '.join(a_list)
print(a_string)

# Raises: TypeError: sequence item 3: expected str instance, int found

In the following sections, you’ll learn how to resolve this error.

Using map() to Convert a List to a String in Python

The map() function allows you to map an entire list of values to another function. This allows you to easily work with heterogenous lists (as we did above). By doing this, we can prevent any TypeErrors from being raised if there are non-string data types.

To learn more about the map() function in Python, check out my in-depth guide. Let’s see how we can use the map() function with the .join() method to convert a list to a string:

# Using map() with .join() to Convert a List to a String
a_list = ['Welcome', 'to', 'datagy.io', 1]

# Option 1:
mapped = map(str, a_list)
a_string = ' '.join(mapped)

# Option 2:
a_string = ' '.join(map(str, a_list))

print(a_string)

# Returns: Welcome to datagy.io 1

Let’s break down what we did in the code block above:

  1. We created a list that contains both strings and an integer
  2. In Option 1 (which works the same way, though a bit more verbose), we created a new mapping object
  3. The mapping object, mapped , uses the map() function and takes the callable of the function we want to map each element of our list to
  4. We then pass that new map object to the .join() method which concatenates the list to a string

In the following section, you’ll learn how to use a for-loop to convert a list to a string.

Using a For Loop to Convert a List to a String in Python

Using a for loop allows you to iterate over each item in a list and append it to a new string. This means that you can easily concatenate a list of values to a string.

Using a For Loop with Lists of Only Strings

Let’s take a look at how this works when working with lists that contain only strings:

# Using a Python for loop to Convert a List to a String in Python
a_list = ['Welcome', 'to', 'datagy.io']
a_string = ''

for item in a_list:
    a_string += item

print(a_string)

# Returns: Welcometodatagy.io

Using a For Loop with Heterogenous Lists

Similar to our previous example, this will raise a TypeError if we attempt to concatenate non-string values. In order to fix this error, we can either:

  1. Check if the item is a string and, if not, convert it
  2. Apply the str() function to each item in the list

Let’s see how we can use the second option, as it requires less code:

# Using a Python for loop to Convert a Heterogenous List to a String in Python
a_list = ['Welcome', 'to', 'datagy.io', 1]
a_string = ''

for item in a_list:
    a_string += str(item)

print(a_string)

# Returns: Welcometodatagy.io1

Using a For Loop with a Separator to Concatenate a List to a String

One thing you’ll notice is that we are simply concatenating the items without any separator. We can also include a separator in the for-loop, in order to make our text cleaner.

Let’s see how we can separate each item with a space in order to make our text cleaner:

# Concatenating a List to a String in Python Using a Separator
a_list = ['Welcome', 'to', 'datagy.io', 1]
a_string = ''

for item in a_list:
    a_string = a_string + ' ' + str(item)

a_string = a_string.strip()

print(a_string)

# Returns: Welcome to datagy.io 1

Let’s break down what we did in the code block above:

  1. We declared our list and empty string
  2. We then looped over each item and appended a space and the string representation of each item to the string
  3. We then applied the .strip() method to our final string, in order to remove a resulting leading space

In the following section, you’ll learn how to use a list comprehension to concatenate a list to a string.

Using a List Comprehension to Convert a List to a String in Python

We can also easily use a list comprehension in combination with the .join() method to convert a list to a string. This allows us to work with lists that contain non-string data types.

Remember, when we attempt to use the .join() method with lists that contain non-string data types, we raise a TypeError. We can resolve this error by first converting each item in the list to a string, by using the str() function within a list comprehension. Let’s see what this looks like:

# Using .join() With Mixed Data Types
a_list = ['Welcome', 'to', 'datagy.io', 1]

comp = [str(item) for item in a_list]
a_string = ' '.join(comp)
print(a_string)

# Returns: Welcome to datagy.io 1

In the code block above, we used a list comprehension to create a string copy of each item in the list. We then passed this new list into our .join() method call.

Using a list comprehension is a clean and fast way to modify items in a list.

What is the Fastest Way to Convert a List to a String in Python?

In this section, we’ll explore what the fastest method to convert a Python list to a string is in Python. In order to test this, we’ll load a list of twenty million elements and convert it to a string.

In the first round of tests, we’ll use a heterogenous list which requires converting the items to strings and then combining them into a resulting string. These tests are more likely to occur since you can’t often guarantee each item will be a string:

MethodTime
.join() with a list comprehension2.5 s
.join() with map()1.69 s
For Loops2.97 s
The fastest way to combine heterogeneous lists into a string

We can see that the .join() method with the map() function is the fastest method, by nearly 33% compared to the second fastest!

Now, let’s take a look at combining heterogenous lists into a string. In order to do this, we only need to compare the .join() method and the for loop method:

MethodTime
.join()205 ms
For loops1.43 s
The fastest way to combine homogenous lists of strings into a string

In this case, the .join() method was significantly faster!

Frequently Asked Questions

What is the Best Way to Convert a List to a String in Python?

The best way to convert a Python list to a string is to use the .join() method. If your list is heterogenous, then map each item in the list to a string using the map() function. If you are certain that your list only contains strings, then simply using the .join() method is the fastest and cleanest way.

What is the fastest way to convert a list to a string in Python?

The fastest way to convert a list to a string is to use the .join() method if the list only contains strings. If your list contains data types that aren’t strings, using .join() and map() together is the fastest method.

Conclusion

In this tutorial, you learned how to use Python to convert a list to a string. You first learned how to do this using the .join() string method. Then, you learned about the complexities of working with lists that may not contain only strings. You learned how to use for loops, list comprehensions, and the map() function to combine lists into strings. Finally, you learned which of these methods is the fastest.

Additional Resources

To learn more about related topics, check out the tutorials below:

Leave a Reply

Your email address will not be published.