Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Selective Merge in String list
Next article icon

Python | Ways to merge strings into list

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Initialize an empty list called “merged”.
  2. 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.
  3. 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.



Next Article
Python | Selective Merge in String list
author
everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Merge Tuple String List values to String
    Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let's discuss certain ways in which this problem can be solved. Method #1: Using l
    6 min read
  • List of strings in Python
    A list of strings in Python stores multiple strings together. In this article, we’ll explore how to create, modify and work with lists of strings using simple examples. Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings. [GFGTABS
    2 min read
  • Python | Selective Merge in String list
    Sometimes, while working with Python lists, we can have a problem in which we need to perform the merge operation. There can be various modifications to merge. One such can be replacing every character except a particular character. Let's see different ways in which this task can be performed. Metho
    5 min read
  • Python | Merge Python key values to list
    Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss
    4 min read
  • Python Program to Convert a List to String
    In Python, converting a list to a string is a common operation. In this article, we will explore the several methods to convert a list into a string. The most common method to convert a list of strings into a single string is by using join() method. Let's take an example about how to do it. Using th
    3 min read
  • Python | Append String to list
    Sometimes, while working with data, we can have a problem in which we need to add elements to a container. The list can contain any type of data type. Let's discuss certain ways in Python in which we can perform string append operations in the list of integers. Example: Append String at the end of a
    5 min read
  • Merge Two Lists into List of Tuples - Python
    The task of merging two lists into a list of tuples involves combining corresponding elements from both lists into paired tuples. For example, given two lists like a = [1, 2, 3] and b = ['a', 'b', 'c'], the goal is to merge them into a list of tuples, resulting in [(1, 'a'), (2, 'b'), (3, 'c')]. Usi
    3 min read
  • Python | List of tuples to String
    Many times we can have a problem in which we need to perform interconversion between strings and in those cases, we can have a problem in which we need to convert a tuple list to raw, comma separated string. Let's discuss certain ways in which this task can be performed. Method #1: Using str() + str
    8 min read
  • Convert String List to ASCII Values - Python
    We need to convert each character into its corresponding ASCII value. For example, consider the list ["Hi", "Bye"]. We want to convert it into [[72, 105], [66, 121, 101]], where each character is replaced by its ASCII value. Let's discuss multiple ways to achieve this. Using List Comprehension with
    3 min read
  • Python | Convert String to list of tuples
    Sometimes, while working with data, we can have a problem in which we have a string list of data and we need to convert the same to list of records. This kind of problem can come when we deal with a lot of string data. Let's discuss certain ways in which this task can be performed. Method #1: Using
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences