Odd slicing behavior?

Dave Opstad dave.opstad at monotypeimaging.com
Wed Jun 22 22:01:24 CEST 2005


Take a look at this snippet:

>>> class L(list):
...   def __init__(self, v):
...     super(L, self).__init__(v)
...   def __setitem__(self, key, value):
...     print key.indices(len(self))
... 
>>> v = L(range(10))
>>> v
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> v[::] = [1]
(0, 10, 1)
>>> v[0:10:1] = [1]
(0, 10, 1)

So both assignments result in slices with exactly the same start, stop 
and step values: 0, 10 and 1. Also, the __setitem__ method is being 
called, not the older __setslice__ method; we can tell this because it 
hit the print statement.

However, actually trying to make a slice assignment on a regular list in 
these two ways behaves differently:

>>> v2 = range(10)
>>> v2[0:10:1] = [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 1 to extended slice of 
size 10
>>> v2[::] = [1]
>>> v2
[1]

So given the equality of their slice representations, why do the v2[::] 
and v2[0:10:1] assignments behave differently? My reading of section 
5.3.3 of the manual suggests that these should behave the same.

If I'm just not seeing something obvious, please let me know!

Thanks,
Dave



More information about the Python-list mailing list