Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert a string representation of list into list in Python
In Python, you may encounter situations where a list is stored as a string representation. This commonly happens when reading data from files, APIs, or user input. Python provides several methods to convert these string representations back into actual list objects.
Using strip() and split()
This method manually removes the square brackets and splits the string by commas. It works well for simple cases but treats all elements as strings ?
string_data = "[Mon, 2, Tue, 5]"
# Given string
print("Given string:", string_data)
print("Type:", type(string_data))
# Convert string to list
result = string_data.strip('[]').split(', ')
# Result and its type
print("Final list:", result)
print("Type:", type(result))
Given string: [Mon, 2, Tue, 5] Type: <class 'str'> Final list: ['Mon', '2', 'Tue', '5'] Type: <class 'list'>
Using json.loads()
The json module can directly convert properly formatted string representations to lists. This method preserves data types but requires valid JSON format ?
import json
string_data = "[21, 42, 15]"
# Given string
print("Given string:", string_data)
print("Type:", type(string_data))
# Convert string to list
result = json.loads(string_data)
# Result and its type
print("Final list:", result)
print("Type:", type(result))
print("Element types:", [type(x) for x in result])
Given string: [21, 42, 15] Type: <class 'str'> Final list: [21, 42, 15] Type: <class 'list'> Element types: [<class 'int'>, <class 'int'>, <class 'int'>]
Using ast.literal_eval()
The ast module's literal_eval() function safely evaluates string representations of Python literals. This is the most flexible and secure method ?
import ast
# Works with mixed data types
string_data = "['hello', 42, 3.14, True]"
# Given string
print("Given string:", string_data)
print("Type:", type(string_data))
# Convert string to list
result = ast.literal_eval(string_data)
# Result and its type
print("Final list:", result)
print("Type:", type(result))
print("Element types:", [type(x) for x in result])
Given string: ['hello', 42, 3.14, True] Type: <class 'str'> Final list: ['hello', 42, 3.14, True] Type: <class 'list'> Element types: [<class 'str'>, <class 'int'>, <class 'float'>, <class 'bool'>]
Comparison
| Method | Preserves Data Types | Security | Best For |
|---|---|---|---|
strip() + split() |
No (all strings) | Safe | Simple string lists |
json.loads() |
Yes | Safe | JSON-formatted strings |
ast.literal_eval() |
Yes | Very safe | Python literal strings |
Conclusion
Use ast.literal_eval() for the safest and most flexible conversion that preserves data types. Use json.loads() for JSON-formatted strings, and strip() + split() only for simple string-only lists.
