6 best methods for Python string to list conversion
Learn the 6 best Python methods for converting strings to lists, such as using list(), split(), list comprehension, and more for Python string manipulation.
Nov 8, 2024 • 6 Minute Read
Data types are important — they define how the data is stored, and what operations can be done on it. Because of these restrictions, you may need to change the type of your data in order to use it effectively. As strings and lists are two of the most popular data types in Python, it’s likely you’ll come across situations where you need to convert a list to a string (or vice versa) so you can access and apply functionality specific to those data types.
In this tutorial, I’ll show you six tried-and-true methods to convert strings into lists in Python. Let’s start by going over what these two data types are, and how they operate in the Python language.
What is a string in Python?
A string is a sequence of characters enclosed in double or single quotes. It is the textual representation of the data. Python doesn't have a character data type, so each character of a string is also treated as a string of length 1. For example, if string = “Pluralsight,” then string[0] is P, and string[2] is l.
The slicing operator colon(:) extracts substrings from a string. For instance, [3:12] extracts a substring from the 3rd to 12th index of the main string. Here, the character in the 3rd index will be included in the output, but the 12th character is excluded.
string = "Pluralsight"
print(string[2:8])
uralsi
What is a list in Python?
A list is a collection of items, and each item can be of a different data type. The items are surrounded by closed brackets ([]), and commas separate each item on the list. The list can be created using square brackets, or the built-in function list().
list1 = ["hi", 12, "pluralsight"]
list2 = list(["hi", 12, "pluralsight"])
How to convert strings to lists in Python
1. The list() method
The built-in method list() takes the iterable as an input and converts it to a list. Interables are a Python object that allows you to loop over and access each element at a time. Examples include list, tuple, string, and dictionary. Let’s understand this with an example.
x = "pluralsight"
print(list(x))
['p', 'l', 'u', 'r', 'a', 'l', 's', 'i', 'g', 'h', 't']
x = " plural sight"
print(list(x))
[' ', 'p', 'l', 'u', 'r', 'a', 'l', ' ', 's', 'i', 'g', 'h', 't']
2. List comprehension
List comprehension is a popular Python technique that creates a list from a range or an iterable object. This technique is popular because it can be done in just a single line of code. The idea is to loop over the string and print each character. Let’s see how it works.
x = "plural sight"
print([i for i in x])
['p', 'l', 'u', 'r', 'a', 'l', ' ', 's', 'i', 'g', 'h', 't']
3. The split() method
The built-in split() method takes the delimiter as an argument and converts the string to a list based on the specified delimiter. If the delimiter is not specified, the default delimiter is whitespace. The split method cannot convert a string into individual characters. Instead, it breaks down the text into separate words or chunks based on the delimiter.
x = "plural sight"
print(x.split())
['plural', 'sight']
As the default delimiter is whitespace, the string “plural sight” is split into “plural”, “sight”.
x = "plural-sight-courses"
print(x.split('-'))
['plural', 'sight', 'courses']
We have set the delimiter as ‘-’, so the string is split accordingly.
4. String slicing
String slicing is a popular method to extract substrings from a string. Combining it with list comprehension can convert a string to a list.
text = "plural sight"
res = [text[i:i+1] for i in range(0, len(text))]
print(res)
['p', 'l', 'u', 'r', 'a', 'l', ' ', 's', 'i', 'g', 'h', 't']
Code explanation: The “text[i:i+1]” returns a substring from the index i to i+1. The for loop in the above code iterates over the string and slices it to get each character. The next code example will help you understand this concept even better.
text = "plural sight"
res = [text[i:i+2] for i in range(0, len(text))]
print(res)
['pl', 'lu', 'ur', 'ra', 'al', 'l ', ' s', 'si', 'ig', 'gh', 'ht', 't']
Code explanation: For each i, the substring length of 2 is extracted because the “text[i:i+2]” part of the code returns a substring from index i to i+2.
5. The enumerate() function
The enumerate() built-in function loops over the string and keeps track of both the index and the corresponding value. Let’s see this with an example.
s="plural sight"
x=[i for y,i in enumerate(s)]
print(x)
Code explanation: In the above code, “y” is the key with index numbers, and “i” refers to the actual string characters. We use list comprehension to iterate over each enumerate object and store the corresponding string character (i) in the list x. Output:
['p', 'l', 'u', 'r', 'a', 'l', ' ', 's', 'i', 'g', 'h', 't']
6. Using ast.literal
Literals represent a constant value that doesn’t change during execution. When you assign a value to a variable, then that constant value is the literal. There are several types of literals. For example, “Pluralsight” is the string literal, 10 is the integer literal, and [1,2,3,4] is the list literal.
import ast
string = "[12,'lion', 15]"
list = ast.literal_eval(string)
print(list)
[12, 'lion', 15]
Conclusion
Hopefully, you have now learned various ways to convert a string into a list. Data type conversions are essential for accessing and using data the way we want. For example, string-to-list conversion turns a string into a list, allowing us to perform all list operations on it.
Python also supports various data type conversions such as integer to float, list to set, dictionary to list, and more. For these, the language provides multiple built-in functions or more straightforward methods.
If you want to learn Python programming, check out Pluralsight’s Python tutorials and online courses. Beginners can start with Python 3 fundamentals, while the advanced Python course is ideal for professional programmers.
FAQs
How to make a list of strings in Python?
Create a list using square brackets ([..]) and place each string separated by commas in the list. That is, string_list = [“plural”, “sight”, “python”].
How to convert string to list with delimiter in Python?
The split() method is used to convert a string to a list based on a delimiter. If no delimiter is specified, the default delimiter is whitespaces.
What is the difference between list() and split()?
The list() constructor breaks the string into a list of individual characters, while the split() method breaks down the string based on a specified parameter.