Python Principles

Converting a string to a list

This post explains how to convert a string to a list in Python.

List of words

If you need a list of words in the given string, use the built-in .split() method on the string. For example:

>>> "this is a test".split()
['this', 'is', 'a', 'test']

If the words are separated by a specific character, you can give that character as an argument to split:

>>> "yet,another,example".split(",")
['yet', 'another', 'example']

If you need to do something with each word, use a for loop like this:

>>> sentence = "this is an example"
>>> for word in sentence.split():
...     print(word)

We have written more about how to split a string in a different post.

List of letters

Sometimes, you need a list where each element is a letter from your string. In this case, use the list() built-in function:

>>> list("abc")
['a', 'b', 'c']

Want to get better at Python?

Try our practical beginner lessons, or test your skills with our challenges.

View Lessons Try Challenges