slice notation as values?

Devan L devlai at gmail.com
Sat Dec 10 15:07:12 EST 2005


Antoon Pardon wrote:
> On 2005-12-10, Duncan Booth <duncan.booth at invalid.invalid> wrote:
[snip]
> >> I also think that other functions could benefit. For instance suppose
> >> you want to iterate over every second element in a list. Sure you
> >> can use an extended slice or use some kind of while. But why not
> >> extend enumerate to include an optional slice parameter, so you could
> >> do it as follows:
> >>
> >>   for el in enumerate(lst,::2)
> >
> > 'Why not'? Because it makes for a more complicated interface for something
> > you can already do quite easily.
>
> Do you think so? This IMO should provide (0,lst[0]), (2,lst[2]),
> (4,lst[4]) ...
>
> I haven't found a way to do this easily. Except for something like:
>
> start = 0:
> while start < len(lst):
>   yield start, lst[start]
>   start += 2
>
> But if you accept this, then there was no need for enumerate in the
> first place. So eager to learn something new, how do you do this
> quite easily?

>>> lst = ['ham','eggs','bacon','spam','foo','bar','baz']
>>> list(enumerate(lst))[::2]
[(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]

No changes to the language necessary.




More information about the Python-list mailing list