32

I am iterating over an array in python:

for g in [ games[0:4] ]:
    g.output()

Can I also initialise and increment an index in that for loop and pass it to g.output()?

such that g.output(2) results in:

Game 2 - ... stuff relating to the object `g` here.
1
  • try using enumerate() method. Commented Aug 11, 2022 at 9:11

2 Answers 2

37

Like this:

for index, g in enumerate(games[0:4]):
    g.output(index)
Sign up to request clarification or add additional context in comments.

Comments

15

Use the built-in enumerate method:

for i,a in enumerate(['cat', 'dog']):
   print '%s is %d' % (a, i)

# output:
# cat is 0
# dog is 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.