Given a tuple that contains multiple lists, the task is to flatten it into a single tuple containing all elements from those lists.
For example:
Input: ([5, 6], [6, 7, 8, 9], [3])
Output: (5, 6, 6, 7, 8, 9, 3)
Let’s explore different Python methods to achieve this task efficiently.
Using itertools.chain()
chain.from_iterable() combines multiple inner lists into a single sequence without creating intermediate lists. It is particularly suitable for large datasets, as it lazily iterates over elements, reducing memory consumption.
from itertools import chain
tup = ([5, 6], [6, 7, 8, 9], [3])
res = tuple(chain.from_iterable(tup))
print(res)
Output
(5, 6, 6, 7, 8, 9, 3)
Explanation:
- chain.from_iterable(tup) iterates through each sublist inside tup and extracts their elements in sequence.
- tuple() converts the flattened sequence into a tuple.
Using list comprehension
List comprehension unpacks each sublist within the tuple and extracts individual elements into a flat tuple.
tup = ([5, 6], [6, 7, 8, 9], [3])
res = tuple(x for sublist in tup for x in sublist)
print(res)
Output
(5, 6, 6, 7, 8, 9, 3)
Explanation:
- for sublist in tup loops through each inner list.
- for x in sublist accesses each element inside the sublist.
- x extracts individual elements.
- tuple() converts the flat sequence into a tuple.
Using functools.reduce()
The reduce() function applies a combining function cumulatively to all elements. Here, it concatenates sublists into one list before converting it into a tuple.
from functools import reduce
tup = ([5, 6], [6, 7, 8, 9], [3])
res = tuple(reduce(lambda x, y: x + y, tup))
print(res)
Output
(5, 6, 6, 7, 8, 9, 3)
Explanation: reduce(lambda x, y: x + y, tup) combines all sublists in tup by repeatedly concatenating pairs of sublists into a single list and tuple() converts the result into a flattened tuple of elements.
Using sum()
sum() can flatten a tuple of lists by summing the sublists , starting with an empty list. Each concatenation creates a new intermediate list, making it memory-intensive and slow for flattening tuples of lists.
tup = ([5, 6], [6, 7, 8, 9], [3])
res = tuple(sum(tup, []))
print(res)
Output
(5, 6, 6, 7, 8, 9, 3)
Explanation: sum(tup, []) concatenates all sublists in tup into a single list, starting with an empty list [], and tuple() converts the result into a flattened tuple of elements.