Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate if list contains unequal tuple in size?

As we already know, if we have a list which contains equal tuple in size then we can iterate through like below,

list1 =[(1,2),(3,4),(5,6)]
for (i,j) in list1:
    print(i,j)

what if I have a list of tuple as below:

list1 =[(1,2,3),(4,5),(7,8,9),(10,11)] 

instead of using nested for loop, is there any other way to iterate through all element?

like image 981
general46 Avatar asked Mar 05 '23 04:03

general46


1 Answers

If you already know the minimum size, you can unpack the minimum and the remainder:

>>> list1 =[(1,2,3),(4,5),(7,8,9),(10,11)] 
>>> for i, j, *r in list1:
...     print(i, j, r)
... 
1 2 [3]
4 5 []
7 8 [9]
10 11 []
like image 73
Netwave Avatar answered Mar 06 '23 16:03

Netwave