13

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?

AShelly
  • 32,752
  • 12
  • 84
  • 142

2 Answers2

8

Something like:

for i, v in enumerate(a):
   print "{} : {}".format(i, v)
AShelly
  • 32,752
  • 12
  • 84
  • 142
klasske
  • 2,094
  • 1
  • 22
  • 29
4

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
gnrhxni
  • 41
  • 1