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)) |
['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) |
['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) |
['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) |
['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 |
['a', 'apple', 'b', 'ball']
Time complexity: O(n)
Auxiliary Space: O(n)