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 - String till Substring
Next article icon

Python | Split Sublist Strings

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

Yet another variation of splitting strings is splitting the strings that are an element of the sublist. This is quite a peculiar problem, but one can get the data in this format, and the knowledge of splitting it anyways is quite useful. Let's discuss certain ways in which this particular task can be performed.

Method #1 : Using list comprehension + split() 

This method is the shorthand version of the longer loop version that one could choose to solve this particular problem. We just split the strings fetching the sublist using the loop in list comprehension using the split function.

Python3
# Python3 code to demonstrate # Split Sublist Strings # using split() + list comprehension  # initializing list test_list = [['GfG is best'], ['All love Gfg'], ['Including me']]  # printing original list print("The original list : " + str(test_list))  # using split() + list comprehension # Split Sublist Strings res = [sub.split() for subl in test_list for sub in subl]  # print result print("The list after splitting strings : " + str(res)) 

Output
The original list : [['GfG is best'], ['All love Gfg'], ['Including me']] The list after splitting strings : [['GfG', 'is', 'best'], ['All', 'love', 'Gfg'], ['Including', 'me']]

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using list comprehension + split() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method #2: Using map() + lambda + split() 

This task can also be performed using the combination of the above 3 functions. The map function binds the splitting logic to each element which is written using the lambda function that uses split function to perform the split.

Python3
# Python3 code to demonstrate # Split Sublist Strings # using map() + lambda + split()  # initializing list test_list = [['GfG is best'], ['All love Gfg'], ['Including me']]  # printing original list print("The original list : " + str(test_list))  # using map() + lambda + split() # Split Sublist Strings res = list(map(lambda sub: sub[0].split(' '), test_list))  # print result print("The list after splitting strings : " + str(res)) 

Output
The original list : [['GfG is best'], ['All love Gfg'], ['Including me']] The list after splitting strings : [['GfG', 'is', 'best'], ['All', 'love', 'Gfg'], ['Including', 'me']]

Method #3: Using itertools.chain()

The itertools.chain() method takes an iterable (such as a list) and returns an iterator that returns the elements of the iterable, one after the other. In this case, the * operator is used to unpack the sublists in test_list and pass their elements as individual arguments to chain(), so that the resulting iterator returns the strings in test_list as a flat list.

The split() method is then used to split each of these strings into a list of substrings. The resulting list comprehension returns a list of lists, where each inner list contains the substrings of a single string in test_list.

Python3
# import the itertools module import itertools  # initializing list test_list = [['GfG is best'], ['All love Gfg'], ['Including me']]  # Flattening test_list and split each string # use the chain() method result = [s.split() for s in itertools.chain(*test_list)]  # Printing the result print(result)  # This code is contributed by Edula Vinay Kumar Reddy 

Output
[['GfG', 'is', 'best'], ['All', 'love', 'Gfg'], ['Including', 'me']]

Time complexity: O(n), where n is the number of elements in test_list. This is because each element in test_list is processed once by chain() and once by split().
Auxiliary space: O(n), for storing results.

Method #4: Using for loop

Python3
test_list = [['GfG is best'], ['All love Gfg'], ['Including me']]  result = []  for sublist in test_list:     for sub in sublist:         result.append(sub.split())          print("The list after splitting strings:", result)  # This  code is contributed by Jyothi pinjala. 

Output
The list after splitting strings: [['GfG', 'is', 'best'], ['All', 'love', 'Gfg'], ['Including', 'me']]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #8: Using a generator expression with split() function

  1. Create a nested list test_list containing 3 sublists with one string element each.
  2. Define a generator expression that uses the split() function to split each string element of the nested list into a list of words.
  3. The generator expression uses a nested loop to iterate through each sublist and string element of the nested list.
  4. Convert the generator expression to a list using the list() function and assign it to the variable res.
  5. Print the result list using the print() function and the str() method.
Python3
# initializing list test_list = [['GfG is best'], ['All love Gfg'], ['Including me']]  # printing original list print("The original list : " + str(test_list))  # using a generator expression with split() function res = (sub.split() for subl in test_list for sub in subl)  # convert generator object to list res = list(res)  # print result print("The list after splitting strings : " + str(res)) 

Output
The original list : [['GfG is best'], ['All love Gfg'], ['Including me']] The list after splitting strings : [['GfG', 'is', 'best'], ['All', 'love', 'Gfg'], ['Including', 'me']]

Time complexity: O(n), where n is the number of elements in the input list.
Auxiliary space: O(n), where n is the total number of characters in the strings in the input list.

Method #6 : Using reduce() and split()

Python3
from functools import reduce  # initializing list test_list = [['GfG is best'], ['All love Gfg'], ['Including me']]  # printing original list print("The original list: " + str(test_list))  # using reduce() and split() to split strings res = [[word for word in sub[0].split()] for sub in test_list]  # print result print("The list after splitting strings: " + str(res)) 

Output
The original list: [['GfG is best'], ['All love Gfg'], ['Including me']] The list after splitting strings: [['GfG', 'is', 'best'], ['All', 'love', 'Gfg'], ['Including', 'me']]

Time Complexity: O(N*M), where N is the number of sublists in the test_list and M is the average number of words in each sublist.
Auxiliary Space: O(K), where K is the total number of words in all sublists combined.


Next Article
Python - String till Substring
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Reversed Split Strings
    In Python, there are times where we need to split a given string into individual words and reverse the order of these words while preserving the order of characters within each word. For example, given the input string "learn python with gfg", the desired output would be "gfg with python learn". Let
    3 min read
  • Python | Splitting string list by strings
    Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let's discuss certain way to solv
    3 min read
  • Python - String till Substring
    When working with Python strings, we may encounter a situation where we need to extract a portion of a string that starts from the beginning and stops just before a specific substring. Let's discuss certain ways in which we can do this. Using split()The split() method is a simple and efficient way t
    3 min read
  • Python - Double Split String to Matrix
    Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix. Examples: Input : test_str = 'Gfg,best*for,all*geeks,and,CS', row_splt = "*", ele_splt = "," Output : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS
    6 min read
  • Python | Split list of strings into sublists based on length
    Given a list of strings, write a Python program to split the list into sublists based on string length. Examples: Input : ['The', 'art', 'of', 'programming'] Output : [['of'], ['The', 'art'], ['programming']] Input : ['Welcome', 'to', 'geeksforgeeks'] Output : [['to'], ['Welcome'], ['geeksforgeeks']
    3 min read
  • Python | Sort all sublists in given list of strings
    Sorting sublists in a list of strings refers to arranging the elements within each sublist in a specific order. There are multiple ways to sort each list in alphabetical order, let's understand each one by one. Using list comprehensionList comprehension with sorted() allows efficient sorting of each
    2 min read
  • Python | K Character Split String
    The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Let’s discuss certain
    4 min read
  • Python | Shift sublist in list
    Sometimes, while working with list, we can have a problem in which we need to shift some sublist to the desired index in the same sublist. This problem can occur in day-day programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using insert() + pop() + loop The comb
    5 min read
  • Python - Selectively Split in Strings
    Sometimes, while working with Python strings, we may have to perform a split. Not sometimes, normal one, depending on deliminator but something depending upon programming constructs like elements, numbers, words etc and segregate them. Lets discuss a way in which this task can be solved. Method : Us
    3 min read
  • Python | Split flatten String List
    Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
    7 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