On Oct 14, 8:00 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Oct 12, 5:58 am, Florian Lindner <[EMAIL PROTECTED]> 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

This yields a value when the iterator is empty, which Diez's solution
didn't. Logically, there is no 'last' element in an empty sequence,
and it's obscure to add one. Peter Otten's improvement to Diez's code
looks the best to me: simple, readable and correct.

--
Paul Hankin

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to