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. 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 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
Sign up to request clarification or add additional context in comments.

3 Comments

@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.
@MYYN don't get your panties in a twist.
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 :)
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

Comments

3
for x in d.keys()[:-1]:
    print x
if d: print "last item:", d.keys()[-1]

11 Comments

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, 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.
@eksorto I did manage to publish a version without the .keys() for a few minutes. @martineau must have seen that one.
@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...
@Apalala: How did you manage to change a published version and not have your answer marked as edited? Inquiring minds what to know... ;-)
|
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 Comment

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

that only works if the last element is not duplicated in the list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.