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 - Replace sublist from Initial element
Next article icon

Python – Merge elements of sublists

Last Updated : 26 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we often need to combine multiple sublists into a single list. This can be useful when dealing with data that is organized in smaller chunks, like rows in a table or pages in a document.

Using itertools.chain()

itertools.chain() function is one of the most efficient ways to merge sublists. It works by combining multiple iterable (like lists) into a single iterable. The best part is that it doesn’t create intermediate lists, making it very memory-efficient. The *a unpacks the list of sublists (a), so each sublist is passed as a separate argument to itertools.chain().

Python
import itertools  # Given list of sublists a = [[1, 2], [3, 4], [5, 6]]  # Merge using itertools.chain b = list(itertools.chain(*a))  # Print the output print(b) 

Output
[1, 2, 3, 4, 5, 6] 

Other methods that we can use to merge sublist in python are:

Table of Content

  • Using extend() with Loop
  • Using sum() Function
  • Using functools.reduce()
  • Using Nested Loop with append()
  • Using numpy.concatenate() (for Numeric Data)

Using extend() with Loop

Another method to merge sublists is by using a loop along with the extend() method. The extend() method allows us to add multiple elements from one list into another list. This method works similarly to list comprehension but is more explicit and can be useful if you prefer using loops.

Python
a = [[1, 2], [3, 4], [5, 6]]  # Initialize an empty list b = []  # Loop through each sublist and extend b with its elements for sublist in a:     b.extend(sublist)  print(b) 

Output
[1, 2, 3, 4, 5, 6] 

Using sum() Function

Although the sum() function is mostly used to add numbers, it can also be used to merge sublists. It works by “adding” all the sublists together, starting from an empty list. However, it’s not the most efficient method, especially for large datasets, because it creates new lists during the process.

Python
a = [[1, 2], [3, 4], [5, 6]]  # Merge using sum b = sum(a, [])  print(b) 

Output
[1, 2, 3, 4, 5, 6] 

Using functools.reduce()

reduce() function from the functools module applies a function repeatedly to combine elements of an iterable. In this case, we can use it to merge sublists. This method is a bit more advanced. reduce() applies the lambda function to combine two lists at a time. The lambda x, y: x + y function takes two lists (x and y) and concatenates them.

Python
from functools import reduce  # Given list of sublists a = [[1, 2], [3, 4], [5, 6]]  # Merge using reduce b = reduce(lambda x, y: x + y, a)  # Print the output print(b) 

Output
[1, 2, 3, 4, 5, 6] 

Using Nested Loop with append()

nested loop with append() is the most manual way to merge sublists. This method gives us full control over the merging process. It’s useful for beginners who are just learning about loops and lists. We create an empty list b. Then, we loop through each sublist in a. For each sublist, we loop through its items and append each item to b using append().

Python
# Given list of sublists a = [[1, 2], [3, 4], [5, 6]]  # Initialize an empty list b = []  # Loop through each sublist and append each item to b for sublist in a:     for item in sublist:         b.append(item)  # Print the output print(b) 

Output
[1, 2, 3, 4, 5, 6] 

Using numpy.concatenate() (for Numeric Data)

If we’re dealing with numerical data and have numpy installed, we can use numpy.concatenate() to merge sublists. It’s highly efficient for large arrays of numbers and works well when you’re already using numpy in your project. numpy.concatenate() takes multiple arrays (or sublists) and combines them into one.

Python
import numpy as np  # Given list of sublists a = [[1, 2], [3, 4], [5, 6]]  # Merge using numpy.concatenate b = np.concatenate(a)  # Print the output print(b) 

Output
[1 2 3 4 5 6] 


Next Article
Python - Replace sublist from Initial element
author
everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • python-list
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python | Get first element of each sublist
    Given a list of lists, write a Python program to extract first element of each sublist in the given list of lists. Examples: Input : [[1, 2], [3, 4, 5], [6, 7, 8, 9]] Output : [1, 3, 6] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['x', 'm', 'a', 'u'] Approach #1 : List comprehe
    3 min read
  • Python | Get last element of each sublist
    Given a list of lists, write a Python program to extract the last element of each sublist in the given list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : [3, 5, 9] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['z', 'm', 'b', 'v'] Approach #1 : List compr
    3 min read
  • Python - Merge list elements
    Merging list elements is a common task in Python. Each method has its own strengths and the choice of method depends on the complexity of the task. This is the simplest and most straightforward method to merge elements. We can slice the list and use string concatenation to combine elements. [GFGTABS
    2 min read
  • Python - Replace sublist from Initial element
    Given a list and replacement sublist, perform the replacement of list sublist on basis of initial element of replacement sublist. Input : test_list = [3, 7, 5, 3], repl_list = [7, 8] Output : [3, 7, 8, 3] Explanation : Replacement starts at 7 hence 7 and 8 are replaced. Input : test_list = [3, 7, 5,
    7 min read
  • Swap tuple elements in list of tuples - Python
    The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
    3 min read
  • Python - Move Element to End of the List
    We are given a list we need to move particular element to end to the list. For example, we are given a list a=[1,2,3,4,5] we need to move element 3 at the end of the list so that output list becomes [1, 2, 4, 5, 3]. Using remove() and append()We can remove the element from its current position and t
    3 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 | Print the common elements in all sublists
    Given a list of lists, the task is to find the elements which are common in all sublist. There are various approaches to do this task. Let's discuss the approaches one by one. Method #1: Using set C/C++ Code # Python code to find duplicate element in all # sublist from list of list # List of list in
    3 min read
  • Python - Group Sublists by another List
    Sometimes, while working with lists, we can have a problem in which we need to group all the sublists, separated by elements present in different list. This type of custom grouping is uncommon utility but having solution to these can always be handy. Lets discuss certain way in which this task can b
    2 min read
  • Python | Split a list into sublists of given lengths
    The problem of splitting a list into sublists is quite generic but to split in sublist of given length is not so common. Given a list of lists and list of length, the task is to split the list into sublists of given length. Example: Input : Input = [1, 2, 3, 4, 5, 6, 7] length_to_split = [2, 1, 3, 1
    2 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