Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a generator that returns ALL-BUT-LAST items in the iterable in Python?

Tags:

python

I asked some similar questions [1, 2] yesterday and got great answers, but I am not yet technically skilled enough to write a generator of such sophistication myself.

How could I write a generator that would raise StopIteration if it's the last item, instead of yielding it?

I am thinking I should somehow ask two values at a time, and see if the 2nd value is StopIteration. If it is, then instead of yielding the first value, I should raise this StopIteration. But somehow I should also remember the 2nd value that I asked if it wasn't StopIteration.

I don't know how to write it myself. Please help.

For example, if the iterable is [1, 2, 3], then the generator should return 1 and 2.

Thanks, Boda Cydo.

[1] How do I modify a generator in Python?

[2] How to determine if the value is ONE-BUT-LAST in a Python generator?

like image 580
bodacydo Avatar asked Mar 11 '10 13:03

bodacydo


2 Answers

This should do the trick:

def allbutlast(iterable):
    it = iter(iterable)
    current = it.next()
    for i in it:
        yield current
        current = i


>>> list(allbutlast([1,2,3]))
[1, 2]

This will iterate through the entire list, and return the previous item so the last item is never returned.
Note that calling the above on both [] and [1] will return an empty list.

like image 108
Dave Kirby Avatar answered Nov 08 '22 18:11

Dave Kirby


First off, is a generator really needed? This sounds like the perfect job for Python’s slices syntax:

result = my_range[ : -1]

I.e.: take a range form the first item to the one before the last.

like image 45
Konrad Rudolph Avatar answered Nov 08 '22 19:11

Konrad Rudolph