0

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()
10
  • 2
    No, there isn't. The normal way would be to do something like en = enumerate(range(1, 10)); for i, e in en: ... Commented Jun 11, 2019 at 20:11
  • 4
    Possible solution for Python 3.8: for idx, number in (en := enumerate(range(1,10))): Commented Jun 11, 2019 at 20:12
  • 1
    @chepner that's beautiful. Commented Jun 11, 2019 at 20:13
  • 3
    @Error-SyntacticalRemorse beauty is in the eye of the beholder. The fights around that PEP were pretty much what drove Guido to step down as BDFL Commented Jun 11, 2019 at 20:17
  • 1
    You have to be careful, too, since next(en) in the loop could raise a StopIteration that the for loop won't catch for you. Commented Jun 11, 2019 at 20:20

1 Answer 1

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

1 Comment

this also simply stores it in a variable to access it. This is just a very convoluted way of doing en = enumerate(range(1, 10)) before the loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.