Last iteration?

Diez B. Roggisch deets at nospam.web.de
Sun Oct 14 07:08:59 EDT 2007


Peter Otten schrieb:
> Diez B. Roggisch wrote:
> 
>> Florian Lindner wrote:
> 
>>> can I determine somehow if the iteration on a list of values is the
>>> last iteration?
> 
>>  def last_iter(iterable):
>>     it = iter(iterable)
>>     buffer = [it.next()]
>>     for i in it:
>>         buffer.append(i)
>>         old, buffer = buffer[0], buffer[1:]
>>         yield False, old
>>     yield True, buffer[0]
> 
> This can be simplified a bit since you never have to remember more than on
> item:
> 
>>>> def mark_last(items):
> ...     items = iter(items)
> ...     last = items.next()
> ...     for item in items:
> ...             yield False, last
> ...             last = item
> ...     yield True, last
> ...
>>>> list(mark_last([]))
> []
>>>> list(mark_last([1]))
> [(True, 1)]
>>>> list(mark_last([1,2]))
> [(False, 1), (True, 2)]

Nice.

I tried to come up with that solution in the first place - but most 
probably due to an java-coding induced brain overload it didn't work 
out:) But I wanted a general purpose based solution to be available that 
doesn't count on len() working on an arbitrary iterable.

Diez



More information about the Python-list mailing list