Welcome, guest | Sign In | My Account | Store | Cart

An method to detect the last item in a loop.

Python, 38 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
Example (and doctest):

>>> for n, islast in iter_islast(range(4)):
...   if islast:
...       print "last but not least:",
...   print n
... 
0
1
2
last but not least: 3

>>> list(iter_islast(''))
[]
>>> list(iter_islast('1'))
[('1', True)]
>>> list(iter_islast('12'))
[('1', False), ('2', True)]
>>> list(iter_islast('123'))
[('1', False), ('2', False), ('3', True)]
>>>
"""

def iter_islast(iterable):
    """ iter_islast(iterable) -> generates (item, islast) pairs

Generates pairs where the first element is an item from the iterable
source and the second element is a boolean flag indicating if it is the
last item in the sequence.
"""

    it = iter(iterable)
    prev = it.next()
    for item in it:
        yield prev, False
        prev = item
    yield prev, True

A question that comes up every once in a while on comp.lang.python is how to detect the last item on a for loop. The proposed solution is usually to use range(len(List)) or enumerate and check the index for len(List)-1. Sometimes the reason for wanting to detect the last item is to avoid printing a trailing comma or other separator. This specific case is best handled with str.join but it is not a general solution.

This recipe makes the code easy to read and works for non-indexable sources like files, generators, itertools objects, etc.

Created by Oren Tirosh on Thu, 17 Mar 2005 (PSF)
Python recipes (4591)
Oren Tirosh's recipes (16)

Required Modules

  • (none specified)

Other Information and Tasks