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
NorthIsUp
  • 17,502
  • 9
  • 29
  • 35
  • 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 Jan 20 '11 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.. http://stackoverflow.com/a/1630350/804616 – trss Jul 13 '14 at 09:51

5 Answers5

30

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
miku
  • 181,842
  • 47
  • 306
  • 310
  • @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 Jan 20 '11 at 19:13
  • @MYYN don't get your panties in a twist. – NorthIsUp Jan 20 '11 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 May 30 '13 at 15:48
5

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
user225312
  • 126,773
  • 69
  • 172
  • 181
3
for x in d.keys()[:-1]:
    print x
if d: print "last item:", d.keys()[-1]
Apalala
  • 9,017
  • 3
  • 30
  • 48
  • `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 Jan 20 '11 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 Jan 20 '11 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 Jan 20 '11 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 Jan 20 '11 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 Jan 20 '11 at 21:39
  • @Apalala: Oh, and if you make a dummy edit to it now, I'll up-vote it. – martineau Jan 20 '11 at 22:14
  • @martineau Mmmm. Post, delete, edit, and undelete within a few minutes, maybe? – Apalala Jan 20 '11 at 23:43
  • @martineau There's your edit. I hope you like the new, more-pythonic version. – Apalala Jan 20 '11 at 23:49
  • @Apalala: I don't think the delete+undelete sequence had anything to do with it. SO shows the first version of your answer as being the one with `for x in d[:-1]:` in it. Perhaps it's due to the fact that there's a short time period after initially posting an answer that you're allowed make last minute changes to it for "free". I always assumed that an answer wasn't visible to others until after this "firming-up" period... – martineau Jan 21 '11 at 05:58
  • @martineau This conversation is verging into meta-land... I don't know what the detailed rules are, and I've failed more than once my promise not to use the SO editor for drafting. – Apalala Jan 21 '11 at 06:17
  • @Apalala: To be honest I really don't think your latest version is anymore Pythonic, but it could be made a tiny bit more efficient if you replaced the references to `d.keys()` with a just `keys` and added a line at the beginning to initialize that with `keys = d.keys()`. Regardless, this approach generally isn't going to work well for determining the "Nth" item in a loop (which is technically what the OP requested although his code example obfuscates that fact). – martineau Jan 21 '11 at 06:21
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

eyquem
  • 26,771
  • 7
  • 38
  • 46
  • 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 May 01 '21 at 07: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

kungfooman
  • 4,473
  • 1
  • 44
  • 33