![]() |
VOOZH | about |
In this article we will explore different methods to iterate through a tuple list of lists in Python and flatten the list into a single list. Basically, a tuple list of lists refers to a list where each element is a tuple containing sublists and the goal is to access all elements in a way that combines the sublists into one continuous list.
zip_longest function from itertools groups elements from each sublist of the list of lists (li) and uses None to fill missing values if the sublists which have different lengths. After that we use list comprehension to remove the None values.
Resultant List: ['11', '21', '31', '12', '22', '32', '13', '23', '33']
Explanation:
This method chains the elements from zip_longest into a single iterable using itertools.chain and then a lambda function is applied to filter out None values before converting the result into a list.
Resultant List: ['11', '21', '31', '12', '22', '32', '13', '23', '33']
Explanation:
List comprehension is used to flatten the list by iterating through each sublist in li and extracting each element.
Resultant List: ['11', '12', '13', '21', '22', '23', '31', '32', '33']
The sum function is used to flatten the list of lists by specifying an empty list [] at the start and then it merges all the sublists into a single list.
Syntax of sum function with 2 arguments is :
sum(iterable, start) where
Resultant List: ['11', '12', '13', '21', '22', '23', '31', '32', '33']
In this method map() is used with a lambda function that simply returns each sublist and itertools.chain flattens the sublists into a single list.
Resultant List: ['11', '12', '13', '21', '22', '23', '31', '32', '33']
Explanation: map(lambda x: x, li) applies the lambda function to each element of li which simply returns each sublist and itertools.chain is used to flatten the list of lists by chaining all the sublists into a single sequence.