La Cordillera
La Cordillera

Reputation: 422

Save iteration number during a for loop in python

I have a list of arrays that I am iterating over with python, so the head of my loop looks like:

for item in my_long_list:
     do_something

My problem is that I want to save the iteration number, so that info can be extracted from another array, something like:

for item in my_long_list:
    do_something
    grab_values(another_long_list[i])

where i is he iteration number that the loop is going through at that moment.

I thought about doing a nested loop like:

for i in list(range(1,len(my_long_list)):
    for item in my_long_list:
        do_something
        grab_values(another_long_list[i])

but it repeats i for each one of the items, when in reality what I want is one single iteration number per item in my long list.

So is there a way to "store" the iteration number and use it within the loop with python?

Upvotes: 0

Views: 1107

Answers (2)

Jun
Jun

Reputation: 21

if you want current item number, maybe you can do this:

for i, v in enumerate(my_long_list,1): # item number from 1 start
    do_something
    grab_values(another_long_list[i])

Upvotes: 1

NotAName
NotAName

Reputation: 4322

You can use the enumerate method that returns the tuple of item number and value.

for iter, i in enumerate(my_long_list)):
    for item in my_long_list:
        do_something
        grab_values(another_long_list[iter])

Upvotes: 4

Related Questions