Pessy
Pessy

Reputation: 21

Get iterator object from inside the loop

I want to get the iteration object from the loop. I want to avoid storing it in another variable and accessing it. Is there a better way to do it, something like get_current_iterator()?

        for idx, number in enumerate(range(1, 10)):
            # need to refer to enum object for use with
            # next()

Upvotes: 0

Views: 57

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195428

for idx, number, en in iter(lambda en=enumerate(range(1, 10)): (*next(en), en), 0):
    print(en, idx, number)

Prints:

<enumerate object at 0x7f74a11b7a68> 0 1
<enumerate object at 0x7f74a11b7a68> 1 2
<enumerate object at 0x7f74a11b7a68> 2 3
<enumerate object at 0x7f74a11b7a68> 3 4
<enumerate object at 0x7f74a11b7a68> 4 5
<enumerate object at 0x7f74a11b7a68> 5 6
<enumerate object at 0x7f74a11b7a68> 6 7
<enumerate object at 0x7f74a11b7a68> 7 8
<enumerate object at 0x7f74a11b7a68> 8 9

Upvotes: 1

Related Questions