14

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
2
  • 2
    As noted below, dictionaries don't have "last items" because their ordering is somewhat arbitrary. So your question, the way it's currently written, is a bit confusing. It's true that you can use for x in d: to iterate over the keys, but those keys are not always sorted in useful ways.
    – eksortso
    Commented Jan 20, 2011 at 19:54
  • Here's a solution that suggests going for handling the first item instead of the last if possible and gives an easy way of detecting that.. stackoverflow.com/a/1630350/804616
    – trss
    Commented Jul 13, 2014 at 9:51

5 Answers 5

31

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
3
  • @The MYYN: Thank you. I think I haven't done any question yet. That's why I never saw a check box outline . I don't understand what is a check box outline , by the way. I will understand later.
    – eyquem
    Commented Jan 20, 2011 at 19:13
  • @MYYN don't get your panties in a twist.
    – NorthIsUp
    Commented Jan 20, 2011 at 21:54
  • Kind of messy compared to what I expected python to be able to do, but not your fault and this is the most elegant solution I can find. Thanks :)
    – 2rs2ts
    Commented May 30, 2013 at 15:48
6

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
3
for x in d.keys()[:-1]:
    print x
if d: print "last item:", d.keys()[-1]
11
  • for x in d[:-1]: gives a TypeError: unhashable type when d = {1:2, 3:4, 5:6, 7:8, 9:0} because dictionary d's values are integers.
    – martineau
    Commented Jan 20, 2011 at 18:49
  • @martineau, try for x in d.keys()[:-1] here instead. @Apalala is iterating over the keys in d, not d itself. The fact that d's values are integers is irrelevant here.
    – eksortso
    Commented Jan 20, 2011 at 19:37
  • @eksorto I did manage to publish a version without the .keys() for a few minutes. @martineau must have seen that one.
    – Apalala
    Commented Jan 20, 2011 at 21:27
  • @eksortso: Gosh, you're right, of course. Improbable as it sounds since the answer doesn't seem to have ever been edited, I swear at one point it was for x in d[:-1]: because I cut & pasted the whole code block as well as the OP's definition of d into a local .py file to generate the exact text of the error message for insertion into my comment. All I can do is take what I wrote back and say "sorry" since it sure appears that I was mistaken...
    – martineau
    Commented Jan 20, 2011 at 21:37
  • 1
    @Apalala: How did you manage to change a published version and not have your answer marked as edited? Inquiring minds what to know... ;-)
    – martineau
    Commented Jan 20, 2011 at 21:39
1
d = {1:2, 3:4, 5:6, 7:8, 9:0}

for i,x in enumerate(d):
    print "last item :"+repr(x) if i+1==len(d) else x

But the last item of an unordered dictionary doesn't mean anything

1
  • Well, yes, it means you wont enter the loop anymore. e.g. : you might want to print them with a “,“ after each, except for a “.“ after the last one.
    – Camion
    Commented May 1, 2021 at 7:49
0
list = [1,2,3]

last = list[-1]

for i in list:
    if i == last:
        print("Last:")
    print i

Output:

1
2
Last:
3

Warning: Only works when the last two elements are not equal

1
  • that only works if the last element is not duplicated in the list.
    – Camion
    Commented May 1, 2021 at 7:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.