Python equivalent of Ruby each_with_index?

In Ruby, if I have an array and I want to use both indexes and 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 python way to do the same?

+5
source share
2 answers

Sort of:

 for i, v in enumerate(a): print "{} : {}".format(i, v) 
+6
source

It will be enumerate .

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

Print

 0 : a 1 : b 2 : c 
+2
source

Source: https://habr.com/ru/post/1201420/


All Articles