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?
for i,x in enumerate(y):
....
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With