Python | Ways to merge strings into list

Given n strings, the task is to merge all strings into a single list.

While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requirement. Let’s understand it better with help of examples.


Method #1: Using ast



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to merge all strings into a single list.
  
# Importing
import ast
  
# Initialization of strings
str1 ="'Geeks', 'for', 'Geeks'"
str2 ="'paras.j', 'jain.l'"
str3 ="'india'"
  
  
# Initialization of list
list = []
  
# Extending into single list
for x in (str1, str2, str3):
    list.extend(ast.literal_eval(x))
  
# printing output
print(list)

chevron_right


Output:

['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'i', 'n', 'd', 'i', 'a']


Method #2: Using eval

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to merge all strings into a single list.
  
# Initialization of strings
str1 ="['Geeks', 'for', 'Geeks']"
str2 ="['paras.j', 'jain.l']"
str3 ="['india']"
  
  
out = [str1, str2, str3]
  
out = eval('+'.join(out))
  
# printing output
print(out)

chevron_right


Output:

['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'india']
filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to merge all strings into a single list.
  
# Initialization of strings
str1 ="'Geeks', 'for', 'Geeks'"
str2 = "'121', '142'"
str3 ="'extend', 'India'"
  
  
out = [str1, str2, str3]
  
out = eval('+'.join(out))
  
# printing output
print(list(out))

chevron_right


Output:

['Geeks', 'for', 'Geeks121', '142extend', 'India']


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.