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
Python - Ways to merge strings into list
While developing an application, there are many scenarios when we need to operate on strings and convert them into mutable data structures like lists. Python provides several ways to merge string representations into a single list.
Using ast.literal_eval()
The ast.literal_eval() method safely evaluates string literals containing Python expressions. This is the recommended approach for converting string representations to lists ?
import ast
# Initialization of strings
str1 = "'Python', 'for', 'fun'"
str2 = "'vishesh', 'ved'"
str3 = "'Programmer'"
# Initialization of list
result_list = []
# Extending into single list
for x in (str1, str2, str3):
result_list.extend(ast.literal_eval(x))
print(result_list)
['Python', 'for', 'fun', 'vishesh', 'ved', 'Programmer']
How It Works
The ast.literal_eval() function parses each string as a tuple of string literals, then extend() adds all elements to the result list.
Using eval() (Not Recommended)
While eval() can merge string representations of lists, it poses security risks and should be avoided ?
# Initialization of strings (list format)
str1 = "['python', 'for', 'fun']"
str2 = "['vishesh', 'ved']"
str3 = "['programmer']"
out = [str1, str2, str3]
out = eval('+'.join(out))
print(out)
['python', 'for', 'fun', 'vishesh', 'ved', 'programmer']
Using List Comprehension with ast.literal_eval()
A more concise approach using list comprehension ?
import ast strings = ["'apple', 'banana'", "'orange'", "'grape', 'kiwi'"] merged_list = [item for s in strings for item in ast.literal_eval(s)] print(merged_list)
['apple', 'banana', 'orange', 'grape', 'kiwi']
Comparison
| Method | Safety | Performance | Best For |
|---|---|---|---|
ast.literal_eval() |
Safe | Good | String literals only |
eval() |
Unsafe | Fast | Never recommended |
| List comprehension | Safe | Best | Concise code |
Conclusion
Use ast.literal_eval() for safe string-to-list conversion. Avoid eval() due to security risks. List comprehension provides the most concise and efficient solution for merging string representations into lists.
