Python | Ways to merge strings into list
Last Updated :
18 Apr, 2023
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
Python3
# 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)
Output:['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'i', 'n', 'd', 'i', 'a']
Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list
Method #2: Using eval
Python3
# 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)
Output:['Geeks', 'for', 'Geeks', 'paras.j', 'jain.l', 'india']
Python3
# 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))
Output:['Geeks', 'for', 'Geeks121', '142extend', 'India']
Method #4: Using replace
Python3
#Initialization of strings
str1 = "'Geeks', 'for', 'Geeks'"
str2 = "'paras.j', 'jain.l'"
str3 = "'india'"
#Split each string by the comma character and remove the single quotes
list1 = [element.replace("'", "") for element in str1.split(",")]
list2 = [element.replace("'", "") for element in str2.split(",")]
list3 = [element.replace("'", "") for element in str3.split(",")]
#Merge the lists into a single list
merged_list = list1 + list2 + list3
#Print the merged list
print(merged_list)
#This code is contributed by Edula Vinay Kumar Reddy
Output['Geeks', ' for', ' Geeks', 'paras.j', ' jain.l', 'india']
The code above is defining three strings, each representing a list of strings separated by a comma. The lists are then split by the comma character and the single quotes are removed from each element. Finally, the lists are merged into a single list.
To split the strings, the split() method is used. This method takes a delimiter as input and returns a list of the elements in the string, separated by that delimiter.
To remove the single quotes from the elements, the replace() method is used. This method takes two arguments: the string to be replaced, and the string to replace it with. In this case, the single quotes are replaced with an empty string, effectively removing them from the element.
The lists are then merged using the + operator.
The time complexity of this code is O(n), where n is the total number of elements in the lists. This is because each element in the lists is processed only once. The space complexity is also O(n), since a new list is created which is the size of the sum of the original lists.
Method#5: Using loop and split.
Algorithm:
- Initialize an empty list called "merged".
- For each string in the input list "out":
a. Remove the brackets from the string using string slicing (i.e. from index 1 to second last index).
b. Split the resulting string at comma and store the resulting list of words in a variable called "words".
c. Extend the "merged" list with the "words" list. - Print the "merged" list.
Python3
# Initialization of strings
str1 = "['Geeks', 'for', 'Geeks']"
str2 = "['paras.j', 'jain.l']"
str3 = "['india']"
out = [str1, str2, str3]
merged = []
for s in out:
# Removing the brackets and splitting the string at comma
words = s[1:-1].split(', ')
merged.extend(words)
# Printing output
print(merged)
#this code contributed by tvsk
Output["'Geeks'", "'for'", "'Geeks'", "'paras.j'", "'jain.l'", "'india'"]
Time complexity: O(nm), where "n" is the length of the input list "out" and "m" is the maximum length of the individual strings in "out".
Auxiliary space complexity: O(nm), to store the "merged" list.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read