- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert a string representation of list into list in Python
As python handles various data types, we will come across a situation where a list will appear in form of a string. In this article we will see how to convert a string into a list.
With strip and split
We first apply the strip method to remove the square brackets and then apply the split function. The split function with a comma as its parameter create the list from the string.
Example
stringA = "[Mon, 2, Tue, 5,]" # Given string print("Given string", stringA) print(type(stringA)) # String to list res = stringA.strip('][').split(', ') # Result and its type print("final list", res) print(type(res))
Output
Running the above code gives us the following result −
Given string [Mon, 2, Tue, 5,] final list ['Mon', '2', 'Tue', '5,']
With json.loads
The json module can make a direct conversion from string to list. We just apply the function by passing the string as a parameter. We can only consider numerical elements here.
Example
import json stringA = "[21,42, 15]" # Given string print("Given string", stringA) print(type(stringA)) # String to list res = json.loads(stringA) # Result and its type print("final list", res) print(type(res))
Output
Running the above code gives us the following result −
Given string [21,42, 15] final list [21, 42, 15]
With ast.literal_eval
The ast module gives us literal_eval which can directly convert the string into a list. We just supply the string as a parameter to the literal_eval method. We can only consider numerical elements here.
Example
import ast stringA = "[21,42, 15]" # Given string print("Given string", stringA) print(type(stringA)) # String to list res = ast.literal_eval(stringA) # Result and its type print("final list", res) print(type(res))
Output
Running the above code gives us the following result −
Given string [21,42, 15] final list [21, 42, 15]