Last iteration?

Paul McGuire ptmcg at austin.rr.com
Sun Oct 14 03:00:42 EDT 2007


On Oct 12, 5:58 am, Florian Lindner <Florian.Lind... at xgm.de> wrote:
> Hello,
> can I determine somehow if the iteration on a list of values is the last
> iteration?
>
> Example:
>
> for i in [1, 2, 3]:
>    if last_iteration:
>       print i*i
>    else:
>       print i
>
> that would print
>
> 1
> 2
> 9
>
> Can this be acomplished somehow?
>
> Thanks,
>
> Florian

Maybe it's a leftover from my C++ days, but I find the iteration-based
solutions the most appealing.  This is a refinement of the previous
post by Diez Roggisch.  The test method seems to match your desired
idiom pretty closely:

def signal_last(lst):
    last2 = None
    it = iter(lst)
    try:
        last = it.next()
    except StopIteration:
        last = None
    for last2 in it:
        yield False, last
        last = last2
    yield True, last

def test(t):
    for isLast, item in signal_last(t):
        if isLast:
            print "...and the last item is", item
        else:
            print item

test("ABC")
test([])
test([1,2,3])

Prints:

A
B
...and the last item is C
...and the last item is None
1
2
...and the last item is 3

-- Paul




More information about the Python-list mailing list