views:

169

answers:

4

Hi,

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?

+19  A: 
for i,x in enumerate(y):
    ....
gnibbler
Thank you, that's wonderful.
foo
BTW, is it good style to put a space between the comma after the i and the x?
chpwn
Yes, it is good style to but a space between the i and the x.
Noctis Skytower
+1  A: 

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
Amber
`cur++` is so unpythonic as to give a syntax error, so it can hardly be recommended;-). I think you mean `cur+=1` (which at least works, though it's grotty when compared to enumerate;-).
Alex Martelli
Thanks. I ended up using enumerate. I'm not sure it makes any difference though, but perhaps manual counting is clearer? Ahem, ok at least for someone not very familiar with Python, looking at the code.
foo
@ Alex, yeah, I actually just finished moving into an apt. so I'm kind of frazzled right now. (And yeah, `enumerate` is much prettier.)
Amber
If you're concerned about someone unfamiliar with Python reading your code, you could always add a brief inline comment explaining enumerate - but frankly, if you name your variables intelligently, it should be quite intuitive. (And 'python enumerate' is an easy search if not!) I wouldn't worry too much.
Rini
A: 

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.)

Isaac
A: 

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.

David Zaslavsky