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.
# Python3 program to unpack # tuple of lists from functools import reduceimport operator def unpackTuple(tup): return (reduce(operator.add, tup)) # Driver code tup = (['a', 'apple'], ['b', 'ball']) print(unpackTuple(tup)) |
['a', 'apple', 'b', 'ball']
Approach #2 : Using Numpy [Alternative to Approach #1]
# Python3 program to unpack # tuple of lists from functools import reduceimport 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 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']
Recommended Posts:
- Unpacking a Tuple in Python
- Python | Unpacking dictionary keys into tuple
- Python | Sort lists in tuple
- Python | Convert a list into tuple of lists
- Python | Find number of lists in a tuple
- Python | Ways to iterate tuple list of lists
- Python | Unpacking nested tuples
- Packing and Unpacking Arguments in Python
- Python - Raise elements of tuple as power to another tuple
- Python | Sort tuple list by Nth element of tuple
- Python | Replace tuple according to Nth tuple element
- Python | Program to count number of lists in a list of lists
- Python | Zipping two lists of lists
- Python | tuple() Function
- Tuple Division in Python
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.

