Python | Ways to iterate tuple list of lists
List is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.
Given a tuple list of lists, write a Python program to iterate through it and get all elements.
Method #1: Use itertools.ziplongest
Python3
# Python code to demonstrate ways to iterate # tuples list of list into single list # using itertools.ziplongest # import library from itertools import zip_longest # initialising listoflist test_list = [ [( '11' ), ( '12' ), ( '13' )], [( '21' ), ( '22' ), ( '23' )], [( '31' ), ( '32' ), ( '33' )] ] # printing initial list print ("Initial List = ", test_list) # iterate list tuples list of list into single list res_list = [item for my_list in zip_longest( * test_list) for item in my_list if item] # print final List print ("Resultant List = ", res_list) |
Initial List = [['11', '12', '13'], ['21', '22', '23'], ['31', '32', '33']] Resultant List = ['11', '21', '31', '12', '22', '32', '13', '23', '33']
Method#2: Using lambda + itertools.chain + zip_longest
Python3
# Python code to demonstrate # ways to iterate tuples list of list into single list # using itertools.ziplongest + lambda + chain # import library from itertools import zip_longest, chain # initialising listoflist test_list = [ [( '11' ), ( '12' ), ( '13' )], [( '21' ), ( '22' ), ( '23' )], [( '31' ), ( '32' ), ( '33' )] ] # printing initial list print ("Initial List = ", test_list) # iterate list tuples list of list into single list # using lambda + chain + filter res_list = list ( filter ( lambda x: x, chain( * zip_longest( * test_list)))) # print final List print ("Resultant List = ", res_list) |
Initial List = [['11', '12', '13'], ['21', '22', '23'], ['31', '32', '33']] Resultant List = ['11', '21', '31', '12', '22', '32', '13', '23', '33']
Method #3: Using List Comprehension
List comprehension is an elegant way to define and create list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp.
Python3
# Python code to demonstrate ways to # iterate tuples list of list into single # list using list comprehension # initialising listoflist test_list = [ [( '11' ), ( '12' ), ( '13' )], [( '21' ), ( '22' ), ( '23' )], [( '31' ), ( '32' ), ( '33' )] ] # printing initial list print ("Initial List = ", test_list) # iterate list tuples list of list into single list # using list comprehension res_list = [item for list2 in test_list for item in list2] # print final List print ("Resultant List = ", res_list) |
Initial List = [['11', '12', '13'], ['21', '22', '23'], ['31', '32', '33']] Resultant List = ['11', '12', '13', '21', '22', '23', '31', '32', '33']