Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the looping index when using Python zip-function?

When simultaneously looping over multiple python lists, for which I use the zip-function, I also want to retrieve the looping index. To this end, a separate list for the looping index may be included in the zip-function, e.g.:

for index, item1, item2 in zip(range(len(list1)), list1, list2):
    <do something>

Is there a better way to do this (like in the enumerate-function)?

like image 919
Rolf Bartstra Avatar asked Apr 14 '26 05:04

Rolf Bartstra


1 Answers

You can unpack everything in the for:

>>> for i, (x1, x2) in enumerate(zip([1,2,3], [3,4,5])):
...     print i, x1, x2
... 
0 1 3
1 2 4
2 3 5
like image 143
DSM Avatar answered Apr 16 '26 19:04

DSM