0

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?

2

2 Answers 2

4

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.