Skip to Content

Convert Python String to a List

In this tutorial, we will look at how to convert a string in Python to a list with the help of some examples.

How to convert a string to a list?

There are two common use cases for converting a string to a list in Python –

  1. Split the string by a delimiter (for example, a whitespace character) and get a list of strings resulting from the split.
  2. Split the string into a list of its constituent characters.

Let’s look at the above two use-cases in detail with the help of some examples.

List to string using string split()

You can use the string split() function to get a list of strings resulting from splitting the original string on the occurrence of a delimiter.

Let’s look at an example –

# create a string
s = "This is Sparta!"
# list from string with split()
ls = s.split()
print(ls)

Output:

['This', 'is', 'Sparta!']

By default the split() function splits the string by a whitespace character. You can see that we get the words in the above string in a list.

You can use your own custom delimiter like comma, underscore, etc. by passing the delimiter as an argument.

String to list using list()

You can use the Python built-in list() function to get a list of the string characters from a string. Pass the string as an argument to the list() function.

Get list from a string in Python

Let’s look at an example. We will use the same string that we used in the example above to see the difference between the two methods and what they are intended for.

# create a string
s = "This is Sparta!"
# list from string with list()
ls = list(s)
print(ls)

Output:

['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'S', 'p', 'a', 'r', 't', 'a', '!']

The resulting list contains each string character as a separate element.

In this tutorial, we looked at two different methods to get a list from a string depending upon your specific use case.

  • To split a string into a list of strings by a delimiter, use the string split() function.
  • To get each character in the string as a list element, use the list() function.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.