Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for x in y, type iteration in python. Can I find out what iteration I'm currently on?

I have a question about the loop construct in Python in the form of: for x in y: In my case y is a line read from a file and x is separate characters. I would like to put a space after every pair of characters in the output, like this: aa bb cc dd etc. So, I would like to know the current iteration. Is it possible, or do I need to use a more traditional C style for loop with an index?

like image 898
foo Avatar asked May 24 '10 01:05

foo


2 Answers

for i,x in enumerate(y):
    ....
like image 181
John La Rooy Avatar answered Sep 19 '22 06:09

John La Rooy


Use enumerate:

for index,x in enumerate(y):
    # do stuff, on iteration #index

Alternatively, just create a variable and increment it inside the loop body. This isn't quite as 'pythonic', though.

cur = 0
for x in y:
    cur += 1
    # do stuff, on iteration #cur
like image 40
Amber Avatar answered Sep 18 '22 06:09

Amber