foo
foo

Reputation: 85

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?

Upvotes: 8

Views: 25626

Answers (4)

David Z
David Z

Reputation: 131690

I can't really make a case that this is better than the enumerate method, but it is less obvious to someone coming from a C perspective, so I thought I'd point it out for completeness:

from itertools import izip_longest
' '.join(j + k for j,k in izip_longest(fillvalue='', *([iter(line)]*2)))

In Python it's often preferred (or at least encouraged) to do something with generators or list comprehensions like this, instead of relying on enumerate.

This is a variation on the grouper method from the itertools module documentation.

Upvotes: 0

Isaac
Isaac

Reputation: 10834

If what you are doing is inserting a space after each pair of characters, you might want to do something with list comprehensions like:

' '.join([''.join(characterPair) for characterPair in zip(*[iter(line + ' ')] * 2)])

Without appending the extra space, the last character of lines with an odd number of characters will be dropped; with the appended space, lines with an odd number of characters will have an extra space at the end.

(There may well be a more pythonic way to do it than what I've done.)

Upvotes: 0

Amber
Amber

Reputation: 527213

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

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304393

for i,x in enumerate(y):
    ....

Upvotes: 23

Related Questions