Monday, August 1, 2011

Python: How to distinguish last loop of iteration

Sometimes you want to treat the last element in a list differently when you're iterating through. Here's how to do that:

prev = None
for x in range(10):
    if prev is not None:
        print "not last:", prev
    prev = x
print "last:", prev

Output:
not last: 0
not last: 1
not last: 2
not last: 3
not last: 4
not last: 5
not last: 6
not last: 7
not last: 8
last: 9

No comments:

Post a Comment