1

I need to loop over an iterable and also have access to an index counter inside that loop:

i = 0
for item in items:
  # ...
  i += 1

Is there more consices Python syntax for doing that, perhaps one that both progresses the iterator and increases the index counter in the same for statement?

1 Answer 1

2

python has an enumerate function:

items = 'abcdef'

for i, item in enumerate(items):
    print(i, item)

which prints:

0 a
1 b
2 c
3 d
4 e
5 f
Sign up to request clarification or add additional context in comments.

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.