Python | Unpacking tuple of lists

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

 

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.