Basically I would like to be able to tell when I'm on the Nth item in a loop iteration. Any thoughts?
d = {1:2, 3:4, 5:6, 7:8, 9:0}
for x in d:
if last item: # <-- this line is psuedo code
print "last item :", x
else:
print x
How about using enumerate?
>>> d = {1:2, 3:4, 5:6, 7:8, 9:0}
>>> for i, v in enumerate(d):
... print i, v # i is the index
...
0 1
1 3
2 9
3 5
4 7
Use enumerate
:
#!/usr/bin/env python
d = {1:2, 3:4, 5:6, 7:8, 9:0}
# If you want an ordered dictionary (and have python 2.7/3.2),
# uncomment the next lines:
# from collections import OrderedDict
# d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
last = len(d) - 1
for i, x in enumerate(d):
if i == last:
print i, x, 'last'
else:
print i, x
# Output:
# 0 1
# 1 3
# 2 9
# 3 5
# 4 7 last
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