6 Ways To Convert String To List Python
In this article, you will learn 6 ways to convert string to list in Python.
When you think of converting a string to a list, then you may come around different cases:
- Converting a sentence to a list of words, each word is a separate element in the list.
- Separating a string at specific places and putting it into a list.
- Converting a string to a list of characters, each character is a separate element in the list.
- Converting a stringified list to list a list.
Quick Solution
If you are in a hurry then here is a quick solution to convert a string to a list.
Use the split() method to convert a string to a list.
Pass a string parameter to the split() method to cut the given string at the specified places. If no argument is passed then it will split the string at the space.
Here is an example to convert a string to a list.
# convert string to list python
str = "Simple Python Code"
print(str.split()) # default split at space
print(str.split(" "))
Output
['Simple', 'Python', 'Code'] ['Simple', 'Python', 'Code']
- Using Split Method
- Python string to list using loop
- Using List Method
- Convert stringified list to list using strip() and split()
- Using slice assignment
- Convert stringified list to list using json.loads()
Table Of Contents
1. Using split Method
The split() is a built-in string method in Python. It splits a string into a specified place and returns a list of strings.
If the string is not specified or is None
, then the algorithm will split the string at the space.
This is the best way to convert string to list in Python.
Convert a string into list of words
# convert string to list of words
str = "Simple Python Code"
print(str.split())
print(str.split(' '))
print(str.split('Python'))
Output
['Simple', 'Python', 'Code'] ['Simple', 'Python', 'Code'] ['Simple ', ' Code']
If you want to check the data type of the list then use the type() method.
# checking data type
str = "Simple Python Code"
print(type(str.split()))
Output
<class 'list'>
2. Python string to list using loop
Loops can be a universal path to solving any repetitive task if you can find the pattern in the problem.
Here we will use for loop to convert a string to a list.
Algorithm:
- Initialize an empty list to store the list of words.
- Initialize an empty string to store the word.
- Loop through each character in the string, if the character is not a space then append it to the string word. Character by character we will get the word.
- If the character is a space (means we found a space) then append the string word to the list.
- At the end of the loop, append the last word to the list.
- Print the list.
Converting a string to a list of words
# convert string to list using for loop
lst = []
word = ''
for char in str:
if char != ' ':
word += char
else:
lst.append(word)
word = ''
# append last word
lst.append(word)
print(lst)
Output
['Simple', 'Python', 'Code']
Using similar logic, we can convert a string to a list of characters.
But this time put every character as a separate element in the list.
Converting a string to a list of characters
# convert string to list of characters
str = "Simple Python Code"
lst = []
for char in str:
lst.append(char)
print(lst)
Output
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']
2.1. Variations Using For loop
Using range() function
# using range to loop String
str = "Simple Python Code"
lst = []
for i in range(len(str)):
if str[i] != ' ':
lst.append(str[i])
else:
lst.append(' ')
print(lst)
Output
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']
Using list comprehension
# using list comprehension
str = "Simple Python Code"
lst = [char for char in str]
print(lst)
Output
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']
3. Python String To List using list() Constructor
The list() constructor returns a list by converting the given object to a list.
The constructor takes a single argument, which is the object to be converted to a list. You can pass any object to the constructor, including a string, a list, a tuple, a dictionary, a set, etc.
Here our need is for a string so we pass the string to the constructor.
# list() constructor
str = "Simple Python Code"
print(list(str))
Output
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']
4. Convert Stringified list to list - Using strip() and split()
Here we want to convert a stringified list to a list. Example of stringified list is: "['Simple', 'Python', 'Code']" and we want to convert it to a list type.
Our approach here is to remove square brackets from the start and end of the stringified list and then split the stringified list using the split() method.
The strip() method removes any combination of given string characters from the beginning and end of a string.
# strip() method
str = "['Simple', 'Python', 'Code']"
print(str.strip("[]"))
Output
'Simple', 'Python', 'Code'
Now split this by using split() method and using ', ' as the separator.
So our complete code is:
str = "['Simple', 'Python', 'Code']"
# strip it
str = str.strip("[]")
# split it
lst = str.split(", ")
print(lst)
print(type(lst))
Output
['Simple', 'Python', 'Code'] <class 'list'>
5. Using Slice Assignment
The slice assignment operator ([:]) is used to insert, delete, or replace a slice of a list.
When you use the slice assignment operator on the left and a string on right, the string is converted to a list and then assigned to the slice.
Here is an example:
# slice assignment
lst = []
str = "Python"
lst[:] = str
print(lst)
Output
['P', 'y', 't', 'h', 'o', 'n']
6. Convert Stringified Number List to List - Using json.loads()
Here we want to convert a stringified list of numbers into a list. An example of a stringified list of numbers is: "[1, 2, 3]" and we want to convert it to a list type.
json.loads() method converts a JSON string to a Python object. We have to import json module first to use this method.
# json.loads() method
import json
# stringified list of numbers
str = "[1, 2, 3, 4, 5]"
lst = json.loads(str)
print(lst)
print(type(lst))
Output
[1, 2, 3, 4, 5] <class 'list'>
Conclusion
In this short guide, you learned 6 different ways to convert string to list python. Most commonly used of all for this purpose is the split() method.
But as now you know 6 different ways but now you can choose to use any depending on your requirement.