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 list of string to list of list in Python
In this article we will see how to convert a list of strings that represent lists into actual nested lists. This is useful when you have string representations of lists and need to convert them back to proper list structures.
Using strip() and split()
The strip() method removes the square brackets, while split() separates the elements by comma and space ?
Example
string_list = ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]']
print("The given list is:")
print(string_list)
print()
# using strip() + split()
result = [item.strip("[]").split(", ") for item in string_list]
print("Converting list of string to list of list:")
print(result)
The given list is: ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]'] Converting list of string to list of list: [['0', '1', '2', '3'], ['"Mon"', '"Tue"', '"Wed"', '"Thu"']]
Using String Slicing and split()
This approach uses slicing [1:-1] to remove the first and last characters (brackets), then applies split() to separate elements ?
Example
string_list = ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]']
print("The given list is:")
print(string_list)
print()
# using string slicing and split()
result = [item[1:-1].split(', ') for item in string_list]
print("Converting list of string to list of list:")
print(result)
The given list is: ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]'] Converting list of string to list of list: [['0', '1', '2', '3'], ['"Mon"', '"Tue"', '"Wed"', '"Thu"']]
Using eval() for Proper Data Types
For converting string representations to actual Python objects with correct data types, use eval() carefully ?
Example
string_list = ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]']
print("The given list is:")
print(string_list)
print()
# using eval() for proper data types
result = [eval(item) for item in string_list]
print("Converting with proper data types:")
print(result)
print("First list type:", type(result[0][0])) # int
print("Second list type:", type(result[1][0])) # str
The given list is: ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]'] Converting with proper data types: [[0, 1, 2, 3], ['Mon', 'Tue', 'Wed', 'Thu']] First list type: <class 'int'> Second list type: <class 'str'>
Comparison
| Method | Data Types Preserved | Safety | Best For |
|---|---|---|---|
strip() + split() |
No (all strings) | Safe | Simple string parsing |
| String slicing | No (all strings) | Safe | Clean syntax |
eval() |
Yes | Use with caution | Trusted input only |
Conclusion
Use strip() and split() for safe string parsing when data types don't matter. Use eval() only with trusted input when you need proper data types preserved.
