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:
Unpacking Dictionary Keys into Tuple - Python
Next article icon

Python | Unpacking tuple of lists

Last Updated : 08 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a tuple of lists, write a Python program to unpack the elements of the lists that are packed inside the given tuple. 

Examples:

Input : (['a', 'apple'], ['b', 'ball']) Output : ['a', 'apple', 'b', 'ball']  Input : ([1, 'sam', 75], [2, 'bob', 39], [3, 'Kate', 87]) Output : [1, 'sam', 75, 2, 'bob', 39, 3, 'Kate', 87]

  Approach #1 : Using reduce() reduce() is a classic list operation used to apply a particular function passed in its argument to all of the list elements. In this case we used add function of operator module which simply adds the given list arguments to an empty list. 

Python3




# Python3 program to unpack
# tuple of lists
from functools import reduce
import operator
 
def unpackTuple(tup):
     
    return (reduce(operator.add, tup))
 
# Driver code
tup = (['a', 'apple'], ['b', 'ball'])
print(unpackTuple(tup))
 
 
Output:
['a', 'apple', 'b', 'ball']

Time complexity: O(n), where n is the total number of elements in all the lists combined in the tuple.
Auxiliary space: O(n), where n is the total number of elements in all the lists combined in the tuple. This is because the reduce function creates a new list that contains all the elements from the input lists.

Approach #2 : Using Numpy [Alternative to Approach #1] 

Python3




# Python3 program to unpack
# tuple of lists
from functools import reduce
import numpy
  
def unpackTuple(tup):
      
    print (reduce(numpy.append, tup))
     
# Driver code
tup = (['a', 'apple'], ['b', 'ball'])
unpackTuple(tup)
 
 
Output:
['a' 'apple' 'b' 'ball']

Approach #3 : Using itertools.chain(*iterables) itertools.chain(*iterables) make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. This makes our job a lot easier, as we can simply append each iterable to the empty list and return it. 

Python3




# Python3 program to unpack
# tuple of lists
from itertools import chain
 
def unpackTuple(tup):
    res = []
    for i in chain(*tup):
        res.append(i)
         
    print(res)
     
# Driver code
tup = (['a', 'apple'], ['b', 'ball'])
unpackTuple(tup)
 
 
Output:
['a', 'apple', 'b', 'ball']

Approach #4: Using extend()

Initialise empty list, iterate over tuple and use extend() method to add list elements to a initialised list.Finally display the new list

Python3




# Python3 program to unpack
# tuple of lists
tup = (['a', 'apple'], ['b', 'ball'])
x=[]
for i in tup:
    x.extend(i)
print(x)
 
 
Output
['a', 'apple', 'b', 'ball']

Approach #5:  Using a list comprehension: This approach involves using a list comprehension to iterate through the elements in the tuple of lists and create a new list containing all the elements. Here’s an example of how it could be done:

Python3




# Tuple of lists
tup = (['a', 'apple'], ['b', 'ball'])
 
# Unpack tuple of lists using list comprehension
unpacked_list = [element for lst in tup for element in lst]
 
print(unpacked_list)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
['a', 'apple', 'b', 'ball']

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



Next Article
Unpacking Dictionary Keys into Tuple - Python

S

Smitha Dinesh Semwal
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Unpacking Nested Tuples-Python
    The task of unpacking nested tuples in Python involves iterating through a list of tuples, extracting values from both the outer and inner tuples and restructuring them into a flattened format. For example, a = [(4, (5, 'Gfg')), (7, (8, 6))] becomes [(4, 5, 'Gfg'), (7, 8, 6)]. Using list comprehensi
    3 min read
  • Unzip List of Tuples in Python
    The task of unzipping a list of tuples in Python involves separating the elements of each tuple into individual lists, based on their positions. For example, given a list of tuples like [('a', 1), ('b', 4)], the goal is to generate two separate lists: ['a', 'b'] for the first elements and [1, 4] for
    2 min read
  • Python - Union of Tuples
    Sometimes, while working with tuples, we can have a problem in which we need union of two records. This type of application can come in Data Science domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using set() + "+" operator This task can be performed using union f
    2 min read
  • Unpacking Dictionary Keys into Tuple - Python
    The task is to unpack the keys of a dictionary into a tuple. This involves extracting the keys of the dictionary and storing them in a tuple, which is an immutable sequence.For example, given the dictionary d = {'Gfg': 1, 'is': 2, 'best': 3}, the goal is to convert it into a tuple containing the key
    2 min read
  • Python Unpack List
    Unpacking lists in Python is a feature that allows us to extract values from a list into variables or other data structures. This technique is useful for various situations, including assignments, function arguments and iteration. In this article, we’ll explore what is list unpacking and how to use
    3 min read
  • Sort Tuple of Lists in Python
    The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
    3 min read
  • Flatten tuple of List to tuple - Python
    The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
    3 min read
  • Python - Create list of tuples using for loop
    In this article, we will discuss how to create a List of Tuples using for loop in Python. Let's suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index. Method 1: Using For loop with append
    2 min read
  • Python - Order Tuples by List
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform ordering of all the tuples keys using external list. This problem can have application in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Input : test_lis
    7 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
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