3 Easy Ways to Convert String to List in Python

String and list are among the most used data types in Python.

Converting them from one to another is a common task in real-life problems.

What is String?

The string is an array of bytes representing Unicode characters. Python does not have a built-in character data type, but a single character is simply a string with a length of 1.

What is a List?

There is no built-in array type but a list data type. Lists can help us store multiple elements in a single variable.

Why convert string to list in Python?

Converting from a string to a list is important because a list can store multiple elements in a single variable, a mutable data type, whereas a string is immutable.

List elements are ordered, modifiable, and allow duplicate values.

Python string to list

To convert string to list in Python, use the string split() method. The split() is a built-in method that splits the strings, stores them in the list, and returns a list of the words in the string, using the “delimiter” as the delimiter string.

If the delimiter is not specified in the function argument or is None, then a different splitting algorithm is applied: its runs of consecutive whitespace are regarded as the single separator.

The result will contain no empty strings at the start or end if the string has a leading or trailing whitespace.

# app.py

def stringToList(string):
    listRes = list(string.split(" "))
    return listRes


strA = "Millie Bobby Brown"
print(stringToList(strA))

See the output.

➜  pyt python3 app.py
['Millie', 'Bobby', 'Brown']
➜  pyt

You can check the data type using the type() function.

# app.py

def stringToList(string):
    listRes = list(string.split(" "))
    return listRes


strA = "Millie Bobby Brown"
print(type(stringToList(strA)))

Output

➜  pyt python3 app.py
<class 'list'>
➜  pyt

Converting string to list using strip() and split()

The strip() method returns the copy of a string with both leading and trailing characters removed based on the string argument passed.

The strip() method removes characters from both left and right based on the argument.

# app.py

initial_list = "[11, 21, 29, 46, 19]"
  
print ("initial string", initial_list) 
print (type(initial_list))
  
op = initial_list.strip('][').split(', ')

print ("final list", op)
print (type(op))

Output

➜  pyt /usr/local/bin/python3 /Users/krunal/Desktop/code/pyt/app.py
initial string [11, 21, 29, 46, 19]
<class 'str'>
final list ['11', '21', '29', '46', '19']
<class 'list'>
➜  pyt

Here, we defined a string that looks like a list.

Then we use the strip() and split() method to convert the string to a list, and finally, we print the list and its type for double-checking.

Converting using AST(Abstract Syntax Trees) module

Python ast module helps Python applications process the trees of abstract syntax grammar.

The abstract syntax might change with each Python release; this module helps determine programmatically what the current grammar looks like.

The abstract syntax tree can be generated by passing the ast.

PyCF_ONLY_AST as the flag to the compile() built-in function or using a parse() helper function provided in this module.

The result will be a tree of objects whose classes inherit from the ast module.

# app.py

import ast

# initializing string representation of a list
ini_list = "[11, 21, 19, 46, 29]"

# printing intialized string of list and its type
print("initial string", ini_list)
print(type(ini_list))

# Converting string to list
res = ast.literal_eval(ini_list)

# printing final result and its type
print("final list", res)
print(type(res))

Output

➜  pyt python3 app.py
initial string [11, 21, 19, 46, 29]
<class 'str'>
final list [11, 21, 19, 46, 29]
<class 'list'>
➜  pyt

Converting string to list using json.loads()

There is a third way to convert the Python string to a list using json.loads() method.

# app.py

import json

# initializing string representation of a list
initial_list = "[11, 21, 19, 46, 29]"

# printing intialized string of list and its type
print("initial string", initial_list)
print(type(initial_list))

# Converting string to list
op = json.loads(initial_list)

# printing final result and its type
print("final list", op)
print(type(op))

Output

➜  pyt python3 app.py
initial string [11, 21, 19, 46, 29]
<class 'str'>
final list [11, 21, 19, 46, 29]
<class 'list'>
➜  pyt

First, we need to import a json module and then use the json.loads() method to convert the string to a list format.

Conclusion

Converting a string to a list in Python can be done in multiple ways. The easiest way to do this is using the split() method. The split() method splits a string into a list using a specified separator string as the delimiter.

Related Posts

Python string to int

Python string to float

Python string to json

Python string to datetime

Python string to dict

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.