How to store some elements from a list into another

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Tue Jun 13 09:24:38 EDT 2017


Peter Otten writes:

...

> def edges(items):
>     first = last = next(items)
>     for last in items:
>         pass
>     return [first, last]

...

> However, this is infested with for loops. Therefore

...

> I don't immediately see what to do about the for loop in edges(), so
> I'll use the traditional cop-out: Removing the last loop is left as an
> exercise...

In the spirit of the exercise:

def sekond(x, y):
    return y

def edges(items): # where items is a non-empty iterator
    first = next(items)
    last = functools.reduce(sekond, items, first)
    return [first, last]

Of course, right?



More information about the Python-list mailing list