Related Articles

Related Articles

Python | Unpacking tuple of lists
  • Difficulty Level : Basic
  • Last Updated : 04 Apr, 2019

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']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :