Slicing versus loops, was Re: for i in range() anti-pattern

Peter Otten __peter__ at web.de
Fri Dec 1 05:15:01 EST 2006


Peter Otten wrote:

> Here is another implementation that cuts maximum memory down from 100 to
> 50%.
> 
> from itertools import islice
> def swap(items):
>     items[::2], items[1::2] = islice(items, 1, None, 2), items[::2]
>     return items

Unfortunately, the following

>>> a = [1, 2, 3]
>>> a[::2] = iter([10, 20, 30])
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
>>> a
[1, 2, 3] 

does not support my bold claim :-( Since the list is not changed there must
be an intermediate copy.

Peter



More information about the Python-list mailing list