How to convert strings to lists in Python
In Python, lists are mutable objects, while strings are immutable. By converting a string into a list, you can modify, add or remove individual characters or subsections of the string.
- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups
What different ways are there to convert Python strings to lists?
When you convert a string into a list, you change the data structure so that it’s able to support list operations. This, in turn, expands the range of data manipulation options that are available to you.
Here are some of the most common methods for converting a string into a list:
split()
The Python split method splits a string into a list of substrings based on a specific separator or pattern. The general syntax for this method is:
string.split(sep=None, maxsplit=-1)
python-
string
: This is the original string. -
sep
(optional): This is the separator where the string is to be split. If no separator is provided, the method defaults to splitting the string at blank spaces. -
maxsplit
(optional):maxsplit
defines the maximum number of splits to be made. If you want Python to carry out all possible splits, you can either set the parameter to -1 or leave it blank.
An example:
text = "blue,green,yellow,red"
print(f"List of colors = {text.split(',')}")
pythonleads to the output:
List of colors = ['blue', 'green', 'yellow', 'red']
pythonf-strings are a Python string format that accept any expression as a placeholder in curly brackets. Using this format, we are able combine the result of the split()
function with the string "List of colors = "
.
list()
The Python list() function is used to convert various data structures, including strings, into lists. If you pass a string as an argument to the list()
function, each letter or character of the string is stored as a separate element in the resulting list.
text = "Hello"
char_list = list(text)
print(char_list)
pythonList comprehension
List comprehension is a compact way to create lists by combining loops and conditions in a single line.
text = "Hello World"
char_list = [char for char in text]
print(char_list)
# Output: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
pythonIn this example, we start with the string "Hello World"
and create a list saved in char_list
. The list comprehension iterates through each letter (char
) in the string text
and adds it as a single element to the list char_list
.
String slicing
String slicing is another method for converting Python strings into lists. It extracts parts of a string (substrings) and saves them as elements in a list.
substring_list = string[start:stop:step]
python-
start
: This is the index where the slicing begins. The substring begins with the character at this position. -
stop
: This is the index where the slicing ends. The sequence includes all characters up to, but not including the character at this position. -
step
(optional): This is the distance between each selected character when slicing is performed. It specifies how many characters should be skipped between each selected character.
convert(string)
is a user-defined function that converts a string into a list of characters. When the expression list1[:0] = string
is executed, the individual characters of the string are inserted into the empty list list1
.
def convert(string):
list1 = []
list1[:0] = string
return list1
str1 = "xyz"
print(convert(str1))
# Output: ['x', 'y', 'z']
pythonre.findall()
You can use the re.findall()
function to convert Python strings into lists by locating all occurrences of a regular expression pattern in a string and retrieving them as a list.
import re
text = "123 and 456 are numbers."
numbers_list = re.findall(r'\d+', text)
print(numbers_list)
# Output: ['123', '456']
pythonThe regular expression r'\d+'
searches for one or more consecutive digits in a text and returns them as separate elements in a list.
enumerate()
The enumerate()
function in Python retrieves both the index and value of each element in an iterable data structure. If you want the list to include only the values (i.e., the characters of the string), you can combine enumerate()
with a list comprehension:
text = "Python"
char_list = [char for index, char in enumerate(text)]
print(char_list)
# Output: ['P', 'y', 't', 'h', 'o', 'n']
pythonJSON
JSON is a module that’s used to read and write JSON data and convert Python data structures into JSON format and vice versa. If you want to convert Python strings to lists using the JSON module, you can do so by parsing a string into a Python object.
import json
json_string = '[1, 2, 3, 4, 5]'
list_from_json = json.loads(json_string)
print(list_from_json)
# Output: [1, 2, 3, 4, 5]
pythonThe json.loads()
function analyzes the JSON string and converts it into a corresponding Python object, in this case, a list.
ast.literal
The ast
(Abstract Syntax Trees) module lets you evaluate a string into a Python data structure, where the string is interpreted as a Python literal. If your string is in a valid Python literal format (like a list, dictionary, number, etc.), you can safely convert it into the corresponding Python object using ast.literal_eval()
.
import ast
string = "[1, 2, 3, 4, 5]"
my_list = ast.literal_eval(string)
print(my_list)
# Output: [1, 2, 3, 4, 5]
pythonFind out more about how converting a string to datetime works in Python in our Digital Guide.