VOOZH about

URL: https://www.geeksforgeeks.org/python/python-unpacking-tuple-of-lists/

⇱ Python | Unpacking tuple of lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Unpacking tuple of lists

Last Updated : 8 Mar, 2023

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. 

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] 

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. 

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


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:


Output
['a', 'apple', 'b', 'ball']

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

Comment