In this article, we will be learning how to convert string to list in python. At first, we must understand the difference between the two. A string in Python can consist of only characters, whereas a list can consist of any data type. So, let us explore the 7 different ways to achieve this conversion.
Ways To Convert String To List In Python
1: Using string.split()
Syntax:
string.split(separator, maxsplit)
Parameters:
- Separator: separator to use when splitting the string
- Default value: whitespace
- maxsplit: number of splits required
Example:
str1 = "Python pool for python knowledge"
list1 = list(str1.split(" "))
print(list1)
Output:
['Python', 'pool', 'for', 'python', 'knowledge']
The split method by default takes whitespace as delimiter and separates the words of the string from by the whitespace and converts them into a list.
2: Using list()
To convert a string into list of characters, we can simply use type conversion using the inbuilt list() method.
Syntax
list(iterable)
Parameter
- iterable: an object that could be a sequence/collection/any iterator object
Example
str1 = "Python pool for python knowledge"
list1 = list(str1)
print(list1)
Output
['P', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'o', 'o', 'l', ' ', 'f', 'o', 'r', ' ', 'p', 'y', 't', 'h', 'o', 'n', ' ', 'k', 'n', 'o', 'w', 'l', 'e', 'd', 'g', 'e']
Using type conversion with the help of list() method, it directly converts the given string into a list of characters for us.
3: Using list(map())
Example
str1 = "Python pool for python knowledge"
str1=str1.split()
list1=list(map(list,str1))
print(list1)
Output
[['P', 'y', 't', 'h', 'o', 'n'], ['p', 'o', 'o', 'l'], ['f', 'o', 'r'], ['p', 'y', 't', 'h', 'o', 'n'], ['k', 'n', 'o', 'w', 'l', 'e', 'd', 'g', 'e']]
In this example, we have used both the split() method and the list() method to obtain the desired result. We first used the split() method to convert the string into a list of strings. We then applied the list() method to an individual element of the list to obtain the list of lists.
4: Using list( map( int, list))
Example
str1="9 8 7 6 5 4 3 2 1"
list1=list(str1.split())
list2=list(map(int,list1))
print(list2)
Output
[9, 8, 7, 6, 5, 4, 3, 2, 1]
In this code, we have first used the split() method to first convert the string into list. We then used type casting to convert the individual elements of the list into integer to get the list of integers as output.
5: Using list( string.split() )
Example
str1 = "Python-pool-for-python-knowledge"
list1 = list(str1.split("-"))
print(list1)
Output:
['Python', 'pool', 'for', 'python', 'knowledge']
In this example, we have used a ‘ – ‘ to split our string and convert it into a list of strings. As the default value of split() is whitespace and in this example, we have used a custom separator ‘ – ‘ to split our string.
6: Using json.loads()
import json
json_str = '{"str": ["Python", "pool", "for", "python", "knowledge"]}'
json_obj = json.loads(json_str)
list1 = json_obj["str"]
print(list1)
Output:
['Python', 'pool', 'for', 'python', 'knowledge']
At first, we have used json.loads() method to convert the JSON string into the dictionary. We then used the index of the dictionary to return the list stored at the index key
.
7: Using ast
import ast
str1 = "['Python', 'pool','for','python', 'knowledge']"
print (type(str1))
print(str1)
list1 = ast.literal_eval(str1)
print (type(list1))
print (list1)
Output:
< class 'str' > [ 'Python' , 'pool' , 'for' , 'python' , 'knowledge' ] < class 'list' > [ 'Python' , 'pool' , 'for' , 'python' , 'knowledge' ]
The ast.literal_eval() is used to evaluate a python expression.
Convert String to List Python Dataframe
.tolist() function will help to change a string present in the column to a list in Python data frame.
Its syntax is :
Col = df.df_name.col_name.tolist()
print(Col)
Convert Multiline String to List Python
To change a multiline string into a list we can use many functions like split(). It takes into account the newline characters. It also looks at the line breaks.
def split_func(str):
return s.split('\n')
print("Before Splitting:")
print("multiline\nstring.\n")
print("After Splitting: ")
print(split_func('multiline\nstring.\n'))
FAQs
You can change strings list to a list with float elements using typecasting.
Its syntax is:print([float(no) for no in listA])
With the help of list comprehension, we can optimize the code and change elements to float.
To change a given string to a list with the string elements, use typecasting in Python.
Example:
code =[ “python” ]
list(code)
print(code)
#this will give the given output: [‘python’]
Conclusion
With this, we come to the end of the article. These are the different ways of converting a string into a list. One can use any of the above methods as per their convenience and requirement.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Happy Pythoning!
Thank you! I’d been struggling all morning to find solution #6.
Thank you very much… Method-7 was very handy.
I had to convert a string which actually had a set of dictionaries as list elements. However, the ast.literal_eval(str) converted it to a tuple. I have to use additional statement like list(ast.literal_eval(str) ) to make it a list.