Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Ruby's each_with_index? [duplicate]

In Ruby, if I have an array and I want to use both the indexes and the values in a loop, I use each_with_index.

a=['a','b','c']
a.each_with_index{|v,i| puts("#{i} : #{v}") } 

prints

0 : a 
1 : b
2 : c

What is the Pythonic way to do the same thing?

like image 435
AShelly Avatar asked Aug 29 '14 13:08

AShelly


2 Answers

Something like:

for i, v in enumerate(a):
   print "{} : {}".format(i, v)
like image 130
klasske Avatar answered Nov 15 '22 22:11

klasske


That'd be enumerate.

a=['a','b','c']
for i,v in enumerate(a):
    print "%i : %s" % (i, v)

Prints

0 : a
1 : b
2 : c
like image 4
gnrhxni Avatar answered Nov 15 '22 22:11

gnrhxni