Python String to List | The Most Pythonic Way

5/5 - (2 votes)
Python String to List | The Most Pythonic Way

Programming is a humbling experience. Seemingly simple things will often surprise you, they’re not so trivial after all. One such example is the string to list conversion. In this article, you’ll learn everything you need to know to convert a string to a list—in different contexts and using different methods.

list(string)Break a string into a list of characters.
[c for c in string]List comprehension for simple character modifications.
lst = []; for c in string: lst.append(c)For more complicated character modifications.
string.split()To break the string into arbitrary substrings using a delimiter.

Problem: Given a string such as 'hello world'. How to convert it to a list ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']?

There are four main ways to accomplish this. You can get a quick overview here:

Exercise: What happens if you try to convert an empty string to a list? Try it!

Let’s dive into the four different methods!

Method 1: list()

The first method uses the default list(iterable) constructor that takes an iterable and creates a new list by iterating over all elements and appending them one by one. Many beginner coders don’t know that strings are also iterables in Python. So, you can pass a string into the list() constructor to obtain a list of characters!

s = 'hello world'
lst = list(s)
# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

This method is best if you want to break up the string into its constituents. But what are the alternatives (and when are they used)? Let’s explore in the next method!

Method 2: List Comprehension

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

You can use list comprehension to iterate over all characters in a string and add them to the list using the identity expression (adding the character unchanged to the new list):

s = 'hello world'
lst = [c for c in s]
# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

This method is best if you want to perform any modification with each (or some) characters from the string before placing them into the new list. For example, you could convert them to UPPERCASE by using the list comprehension statement [c.upper() for c in s]:

lst = [c.upper() for c in s]
# ['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']

You can learn more about list comprehension in the following video:

A Simple Introduction to List Comprehension in Python

Method 3: Simple Loop

A third method to convert a string to a list is to use a simple for loop:

s = 'hello world'
lst = []
for c in s:
# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

Don’t underestimate this! The big advantage of using a for loop is its flexibility. You can easily perform complicated operations with each character in a multi-line loop body. This is not possible with both previous methods!

Method 4: split()

Finally, you may not want to break up the string into its individual characters. Another way to convert a string to a list is to use the split() method that breaks a string into substrings using whitespaces as delimiters:

s = 'hello world'
lst = s.split()
# ['hello', 'world']

You can also modify the delimiter string by passing it into the split() function. For example, s.split('o') would create a list with three substrings ['hell', ' w', 'rld'].

There is also a regular expression variant of the split() function that is even more powerful because it allows you to split on an arbitrary pattern like any number of whitespaces, etc. This article describes this advanced Python feature in more detail.

How to Convert the List of Strings Back to a String?

The reverse operation of the methods discussed here is the string.join() method.

The string.join(iterable) method concatenates all the string elements in the iterable (such as a list, string, or tuple) and returns the result as a new string. The string on which you call it is the delimiter string—and it separates the individual elements. For example, '-'.join(['hello', 'world']) returns the joined string 'hello-world'.

>>> '-'.join(['hello', 'world'])

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!