list.clear() missing?!?
Duncan Booth
duncan.booth at invalid.invalid
Thu Apr 13 03:49:11 EDT 2006
Raymond Hettinger wrote:
> Cons:
> -----
>
> * learning slices is basic to the language (this lesson shouldn't be
> skipped)
>
also, a clear method would simply clear the entire list. You still need to
learn the assigning to/deleting slices technique any time you want to clear
out part of a list.
Every so often I still get an "oh, I didn't know Python could do *that*
moment", just had one now:
>>> s = range(10)
>>> s[::2] = reversed(s[::2])
>>> s
[8, 1, 6, 3, 4, 5, 2, 7, 0, 9]
I've no idea when I might need it, but it just never occurred to me before
that you can also assign/del non-contiguous slices.
The symmetry does breaks down a bit here as assigning to an extended slice
only lets you assign a sequence of the same length as the slice, so you
can't delete an extended slice by assignment, only by using del.
>>> s = range(10)
>>> del s[::2]
>>> s
[1, 3, 5, 7, 9]
>>> s = range(10)
>>> s[::2] = []
Traceback (most recent call last):
File "<pyshell#19>", line 1, in -toplevel-
s[::2] = []
ValueError: attempt to assign sequence of size 0 to extended slice of size
5
>>>
More information about the Python-list
mailing list