Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output an index while iterating over an array in python [duplicate]

Tags:

python

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.
like image 647
BeeBand Avatar asked Jun 06 '10 14:06

BeeBand


2 Answers

Like this:

for index, g in enumerate(games[0:4]):
    g.output(index)
like image 182
tzaman Avatar answered Nov 20 '22 20:11

tzaman


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
like image 40
Mark Rushakoff Avatar answered Nov 20 '22 20:11

Mark Rushakoff