# slice notation as values?

Antoon Pardon apardon at forel.vub.ac.be
Mon Dec 12 09:34:37 CET 2005

```Op 2005-12-10, Devan L schreef <devlai at gmail.com>:
>
> 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')]

Now let me see, in order to just iterate over the even elements
of a list with the index of the element, you turned an iterator
into a list, which you use to create an other list which you
will finaly iterate over.

If this is the proposed answer, I wonder why iterators were introduced
in the first place. I thought iterator were went to avoid the need
to construct and copy list when all you want is iterate and when
I ask how to get a specific iterator you come with a construct that
makes rather heavily use of list constructions.

--
Antoon Pardon

```