473,320 Members | 1,993 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

list.clear() missing?!?

I tried to clear a list today (which I do rather rarely, considering
that just doing l = [] works most of the time) and was shocked, SHOCKED
to notice that there is no clear() method. Dicts have it, sets have it,
why do lists have to be second class citizens?

Apr 11 '06
77 16929
Peter Hansen wrote:
* learning slices is basic to the language (this lesson shouldn't be
skipped)
And yet it doesn't appear to be in the tutorial. I could have missed
it, but I've looked in a number of the obvious places, without
actually going through it (again) from start to finish. Also,
googling for "slice site:docs.python.org", you have to go to the
*sixth* entry before you can find the first mention of "del x[:]" and
what it does. I think given the current docs it's possible to learn
all kinds of things about slicing and still not make the non-intuitive
leap that "del x[slice]" is actually how you spell "delete contents of
list in-place".


Looking in the 'obvious' place in the Tutorial, section 5.1 'More on
Lists' I found in the immediately following section 5.2 'The del
statement':
There is a way to remove an item from a list given its index instead
of its value: the del statement. Unlike the pop()) method which
returns a value, the del keyword is a statement and can also be used
to remove slices from a list (which we did earlier by assignment of an
empty list to the slice).
The 'earlier showing assignment of an empty list to a slice' is a reference
to section 3.1.4 'Lists':
Assignment to slices is also possible, and this can even change the
size of the list:

# Replace some items: ... a[0:2] = [1, 12] a [1, 12, 123, 1234] # Remove some: ... a[0:2] = [] a

[123, 1234]


Both of these talk about ways to remove slices from a list. Perhaps the
wording could be clearer to make it obvious that they can also be used to
clear a list entirely (using the word 'clear' would certainly help people
Googling for the answer). So maybe 'this can even change the size of the
list or clear it completely' would be a good change for 3.1.4.
Apr 13 '06 #51
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

Apr 13 '06 #52
Duncan Booth wrote:
Peter Hansen wrote:
* learning slices is basic to the language (this lesson shouldn't be
skipped)
And yet it doesn't appear to be in the tutorial. I could have missed

Both of these talk about ways to remove slices from a list. Perhaps the
wording could be clearer to make it obvious that they can also be used to
clear a list entirely (using the word 'clear' would certainly help people
Googling for the answer). So maybe 'this can even change the size of the
list or clear it completely' would be a good change for 3.1.4.


I added two examples of clearing a list to the section about slice assignment
and del.

Georg
Apr 13 '06 #53
On Thu, 13 Apr 2006 07:49:11 +0000, Duncan Booth wrote:
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.


A clear method does not *necessarily* clear only the entire list. That's
an choice that can be made. I for one would vote +1 for clear taking an
optional index or slice, or two indices, to clear only a part of the list.

--
Steven.

Apr 13 '06 #54
On Thu, 13 Apr 2006 09:11:31 +0200, Fredrik Lundh wrote:
Peter Hansen wrote:
It's not even clear that extend needs two lines:
>>> s = range(5)
>>> more = list('abc')
>>> s[:] = s + more
>>> s

[0, 1, 2, 3, 4, 'a', 'b', 'c']

Okay, it's not obvious, but I don't think s[:]=[] is really any more
obvious as a way to clear the list.

Clearly .extend() needs to be removed from the language as it is an
unnecessary extension to the API using slicing


you just flunked the "what Python has to do to carry out a certain operation"
part of the "how Python works, intermediate level" certification.


So implementation details are part of the language now?

Out of curiosity, are those things that Python has to do the same for
CPython, Jython, IronPython and PyPy?

Personally, I think it is a crying shame that we're expected to be experts
on the specific internals of the Python interpreter before we're allowed
to point out that "only one obvious way to do it" just is not true, no
matter what the Zen says.
L = []
L.append(0)
L[:] = L + [1]
L[:] += [2]
L[len(L):] = [3]
L.__setslice__(len(L), -1, [4])
L.__setslice__(sys.maxint, sys.maxint, [5])
L += [6]
L

[0, 1, 2, 3, 4, 5, 6]

That's at least seven ways to do an append, and it is a double-standard to
declare that slice manipulation is the One and Only True obvious way
to clear a list, but slice manipulation is not obvious enough for
appending to a list.

No doubt under the hood, these seven ways are implemented differently.
They certainly differ in their obviousness, and I'm willing to bet that
practically nobody thinks that the slicing methods are more obvious than
append. Perhaps we're not Dutch. I daresay one method is better, faster,
or more efficient than the others, but remember the warning against
premature optimisation.

Whenever I see "only one obvious way to do it" being used as a knee-jerk
excuse for rejecting any change, my eyes roll. Nobody wants Python to
turn into Perl plus the kitchen sink, but it isn't as if Python is some
absolutely minimalist language with two objects and three functions. There
is no shortage of "more than one way to do it" convenience methods,
functions and even entire modules. And that's why Python is such a fun,
easy to use language: because most things in Python are just convenient.
When you want to append to a list, or insert into a list, you don't have
to muck about with slices, you call the obvious list method.

And so it should be for clearing all or part of a list.

--
Steven.

Apr 13 '06 #55
Alan Morgan wrote:
Ah, but if you know your basic python then you wouldn't be looking for
s.clear() in the first place; you'd just use s[:]=[] (or s=[], whichever
is appropriate).
One of very first things newcomers learn (I believe, though I don't know
how soon the tutorial teaches it) is to use "dir()" on objects. The
clear() method would show up there and quickly attract attention.
Neither of the other techniques are likely to be discovered as quickly.
(Well, okay, s=[] would be, I'm sure, but to many newcomers that might
"feel wrong" as the way to empty out a list, but then we're back to
wondering how often there's really a usecase for doing so.)
Personally, it seems more *reasonable* to me, a novice python user,
for s.clear() to behave like s=[] (or, perhaps, for s=[] and s[:]=[] to
mean the same thing). The fact that it can't might be an argument for
not having it in the first place.


Then it's a good reason we had this thread, so you could learn something
*crucial* to understanding Python and writing non-buggy code: name
binding versus variables which occupy fixed memory locations like in
some other languages. This has to be by far the most frequent area that
newcomer's trip up. But that's another story...

-Peter

Apr 13 '06 #56
Duncan Booth wrote:
Peter Hansen wrote:
Looking in the 'obvious' place in the Tutorial, section 5.1 'More on
Lists' I found in the immediately following section 5.2 'The del
statement':
There is a way to remove an item from a list given its index instead
of its value: the del statement. Unlike the pop()) method which
returns a value, the del keyword is a statement and can also be used
to remove slices from a list (which we did earlier by assignment of an
empty list to the slice).

I saw that section too, but was scanning for any example of wiping out
the whole list. As you point out, it's not mentioned. I don't think
there's even an example of slicing with no arguments [:] for copying a
list (i.e. on the right side of the =), and it's reasonable to assume (I
originally did, as I recall) that this would be some kind of error...
Both of these talk about ways to remove slices from a list. Perhaps the
wording could be clearer to make it obvious that they can also be used to
clear a list entirely (using the word 'clear' would certainly help people
Googling for the answer). So maybe 'this can even change the size of the
list or clear it completely' would be a good change for 3.1.4.


This is quite true. After all, who imagines when offered a "slice of
cake" that a slice might be the entire thing! The concept of "slice" in
English strongly implies a *subset*, not the whole, so if we're not
going to get a .clear() method, I do believe that the various uses of
[:] should be much more explicitly pointed out in the docs. At least
we'd have a ready place to point to in the tutorial, instead of this
discussion cropping up every month.

-Peter

Apr 13 '06 #57
Peter Hansen wrote:
One of very first things newcomers learn (I believe, though I don't know
how soon the tutorial teaches it)


let's see. lists are introduced on page 19, a more extensive discussion of lists is
found on page 33, the del statement appears on page 34, and the dir() function
is introduced on page 46.

(page numbers from the current pytut PDF copy)

</F>

Apr 13 '06 #58
Alan Morgan wrote:
In article <11**********************@u72g2000cwu.googlegroups .com>,
Raymond Hettinger <py****@rcn.com> wrote:
* s.clear() is more obvious in intent


Serious question: Should it work more like "s=[]" or more like
"s[:]=[]". I'm assuming the latter, but the fact that there is
a difference is an argument for not hiding this operation behind
some syntactic sugar.

It has to work more like s[:]=[]

It's not easy for an object method to bind a whole different
object to the first object's name. Generally only
statements can affect namespaces (hence the uses of del that
everyone remembers.)

Mel.
Apr 13 '06 #59
Steven D'Aprano wrote:
Convenience and obviousness are important for APIs -- that's why lists
have pop, extend and remove methods. The only difference I can see between
a hypothetical clear and these is that clear can be replaced with a
one-liner, while the others need at least two, e.g. for extend:

for item in seq:
L.append(item)


Both extend and append have one-line slice equivalents,
except that the equivalents have to keep referring to
the length of the list.. (have to keep finding the
len function.)

Mel.
Apr 13 '06 #60
Fredrik Lundh wrote:
Peter Hansen wrote:
One of very first things newcomers learn (I believe, though I don't know
how soon the tutorial teaches it)


let's see. lists are introduced on page 19, a more extensive discussion of lists is
found on page 33, the del statement appears on page 34, and the dir() function
is introduced on page 46.


You're spending a lot of time trying to convince me I'm wrong, yet until
Georg did something about it just now, nowhere in those sections did
it talk about [:] specifically, which is sort of the whole point. It is
*not* obvious that although [x:] and [:y] and [x:y] take subsets of
things, that leaving them both out is either legal or useful.

Thankfully (to Georg), it now is. (Well, I haven't read it yet, but
I'll take his word for it.)

-Peter

Apr 13 '06 #61
Peter Hansen wrote:
You're spending a lot of time trying to convince me I'm wrong
no, I'm just posting observable facts in response to various "I'm too
lazy to look this up, but I'll assume that things are this way" posts.
Thankfully (to Georg)


it's fixed in the wiki too...

talking about the wiki, are you and rurpy the same person, btw? the
implied "I'm going to pretend that you've never done anything to im-
prove the situation" insinuations are getting a bit tiresome...

</F>

Apr 13 '06 #62
I agree. Lists should have a clear method. But what's shocking is that
it doesn't seem obvious to others. list.clear() is a whole lot more
readable, intuitive, "flowable" and desirable than del list. Or maybe I
haven't had enough coffee this morning. I'd go as far as saying all
container objects should have a clear method. This is the reason why
those Rubyist whine about Python being inconsistent and not being "OO
enough."

Apr 13 '06 #63

[Mystilleef]
Lists should have a clear method. But what's shocking is that
it doesn't seem obvious to others. list.clear() is a whole lot more
readable, intuitive, "flowable" and desirable than [the alternatives]


+1 to all of that.

--
Richie Hindle
ri****@entrian.com
Apr 13 '06 #64
gry
A perspective that I haven't seen raised here is inheritance.
I often say
mylist = []
if I'm done with the current contents and just want a fresh list.

But the cases where I have really needed list.clear [and laboriously
looked for it and ended up with
del l[:]
were when the object was my own class that inherits from list, adding
some state and other functionality. Of course I *could* have added my
own 'clear' function member, but I *wanted* it to behave like a
standard
python list in it's role of maintaining a sequence of processing steps.
So, I end up doing
del current_process[:]
which, IMO, looks a bit queer, especially when current_process
object is a fairly elaborate data object.

Apr 13 '06 #65
Raymond Hettinger wrote:
[Steven Bethard]
I think these are all good reasons for adding a clear method, but being
that it has been so hotly contended in the past, I don't think it will
get added without a PEP. Anyone out there willing to take out the best
examples from this thread and turn it into a PEP?
Something this small doesn't need a PEP. I'll just send a note to
Guido asking for a pronouncement.


Thanks. It'd be nice to have something to refer to the next time this
comes up.
Here's a draft list of pros and cons (any changes or suggestions are
welcome):

Pros:
-----

* s.clear() is more obvious in intent

* easier to figure-out, look-up, and remember than either s[:]=[] or
del s[:]

* parallels the api for dicts, sets, and deques (increasing the
expecation that lists will too)

* the existing alternatives are a bit perlish

I'd snip the one below. It doesn't really contribute anything, and was
sarcastic in the first place. ;)
* the OP is shocked, SHOCKED that python got by for 16 years without
list.clear()
Cons:
-----

* makes the api fatter (there are already two ways to do it)

* expanding the api makes it more difficult to write classes that can
be polymorphically substituted for lists

* learning slices is basic to the language (this lesson shouldn't be
skipped)

* while there are valid use cases for re-using lists, the technique is
already overused for unsuccessful attempts to micro-optimize (creating
new lists is surprisingly fast)

In fairness, if we're going to drop the "SHOCKED" comment, we should
drop the first two clauses of the point below (but the "relevant idiom"
part is clearly a good point).
* the request is inane, the underlying problem is trivial, and the
relevant idiom is fundamental (api expansions should be saved for rich
new functionality and not become cluttered with infrequently used
redundant entries)


Other than those minor edits, I think you've pretty much gotten
everything. I look forward to a pronouncement.

Thanks again!

STeVe
Apr 13 '06 #66
Mel Wilson wrote:
for item in seq:
L.append(item)


Both extend and append have one-line slice equivalents,
except that the equivalents have to keep referring to
the length of the list.. (have to keep finding the
len function.)


fwiw, the *tutorial* defines append and extend in terms of slicing...

</F>

Apr 13 '06 #67
> > * the request is inane, the underlying problem is trivial, and the
relevant idiom is fundamental (api expansions should be saved for rich
new functionality and not become cluttered with infrequently used
redundant entries)
Is this sort of editorialising fair, or just a way of not-so-subtly
encouraging Guido to reject the whole idea, now and forever?


Bah. Guido is not stupid, nor easily misled. Both the pros and cons
were quipped with abrupt perjoratives so the bullet points could be
stated succinctly and with a bit of levity. The translation to
verbose, soft, politically correct statements is self-evident.

"request is inane" --> "A generation of python programmers has found
list clearing to be like other parts of the language that you get used
to very quickly and do not prove to be a problem in practice. The
request is in the same category as others which challenge api choices
made 16 years ago; in particular, the decision to have compact APIs
where the named methods do not duplicate functionality provided by
syntax using operators and keywords. The request is less of a bug
report and more a rejection of Guido's sense of design and his
subsequent experience using his own language."

"underlying problem is trivial" --> "Books such as the Python Pocket
Reference or Python in a Nutshell are able to cover this idiom with
just a single sentence. Once known and understood, the application of
the current-way-to-do-it is immediate, compact, and effective."

"the existing alternatives are a bit perlish" --> "Both alternatives
involve a bit of inventiveness in combining two ideas (either the del
keyword and its interaction with slicing notation or the assignment of
an emtpy list to a slice). Each approach has a visual appearance of
being a syntax trick. The effect contrasts with much of the rest of
the language where it is usually possible to write code is a way that
can be read and understood by non-python programmers. The existing
solution trades readability for the succinctness of a compact
syntactical idiom."
A list.clear method will make deleting items from a list more OO,
consistent with almost everything else you do to lists, and less
procedural. This is especially true if clear() takes an optional index (or
two), allowing sections of the list to be cleared, not just the entire
list.


Don't shoot yourself in the foot here. If you want to advocate
list.clear(), then you're hurting your chances by pushing for it to
take an optional argument. Essentially, this amounts to an
unwillingness to use the del-keyword and to duplicate its functionality
with a named method.

Also, in the python-dev world, making something "more OO" is neither a
virtue nor a vice. It is better to argue for rich functionality,
succeptibility to errors, or dramatic improvements of existing
real-world code.

Apr 13 '06 #68
Raymond Hettinger wrote:
Also, in the python-dev world, making something "more OO" is neither a
virtue nor a vice.


except that arguments along the line of "if the syntax is not obj.method(),
it's not OO enough" are likely to be mostly ignored.

(nobody's going to be impressed by yet another "len(obj) isn't OO" variant)

</F>

Apr 13 '06 #69
Fredrik Lundh <fr*****@pythonware.com> wrote:
except that arguments along the line of "if the syntax is not obj.method(),
it's not OO enough" are likely to be mostly ignored.

(nobody's going to be impressed by yet another "len(obj) isn't OO" variant)


Does that suggest that what's needed is clear(obj) and __clear__
methods? 8-)

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Apr 13 '06 #70
[Dan Christensen]
It's true that this runs at the same speed as the del variants on my
machine. That's not too surprising to me, but I still don't
understand why the del variants are more than 5% faster than the first
version.
Understanding it involves looking at implementation specific details
such as the overallocation scheme for growing lists and the performance
of your machine's underlying memory allocator.

Once this is understood, is it something that could be optimized?
It's pretty common to rebind a variable to a new value, and if
this could be improved 5%, that would be cool.


Sorry, that's not how the language works. Something like
"a=range(100000)" means:
* build a NEW list for 100000 elements
* THEN assign it to the variable "a"
* which THEN reduces the ref count to the previous binding for "a"
* and THEN IF the ref count is zero, free the list previously bound to
"a"

In other words, if "a" is already bound to a large list, then the above
assignment necessarily creates a second, non-overlapping list in
memory.

However, if you write "a=None;a=range(100000)", then the original list
gets freed BEFORE the new list is created and the system has a chance
to re-use that large, contiguous block of memory.

Apr 13 '06 #71
Peter Hansen <pe***@engcorp.com> writes:
[...]
Then it's a good reason we had this thread, so you could learn something
*crucial* to understanding Python and writing non-buggy code: name
binding versus variables which occupy fixed memory locations like in
some other languages. This has to be by far the most frequent area that
newcomer's trip up. But that's another story...


I, as a newcomer, don't have much trouble understanding the binding vs
the assignment by themselves. What does somewhat confuse is dual role of
the "=" operator, -- sometimes it means "bind" and other times it means
"assign", right? For me it seems that the language would be less
error-prone and easier to grok if these two operations had different
names/syntax (thinking about lisp "let" vs "set"), though it seems to be
too drastic change even for Python3000.

-- Sergei.

Apr 14 '06 #72
Em Sex, 2006-04-14 Ã*s 09:17 +0400, Sergei Organov escreveu:
I, as a newcomer, don't have much trouble understanding the binding vs
the assignment by themselves. What does somewhat confuse is dual role of
the "=" operator, -- sometimes it means "bind" and other times it means
"assign", right? For me it seems that the language would be less
error-prone and easier to grok if these two operations had different
names/syntax (thinking about lisp "let" vs "set"), though it seems to be
too drastic change even for Python3000.


The "=" operator *always* binds.

--
Felipe.

Apr 14 '06 #73
Dennis Lee Bieber <wl*****@ix.netcom.com> writes:
On Fri, 14 Apr 2006 09:17:05 +0400, Sergei Organov <os*@javad.com>
declaimed the following in comp.lang.python:

I, as a newcomer, don't have much trouble understanding the binding vs
the assignment by themselves. What does somewhat confuse is dual role of
the "=" operator, -- sometimes it means "bind" and other times it means
"assign", right? For me it seems that the language would be less


It always means bind... But if the LHS is a mutable object, AND you
have specified a component of that object, it is the component that is
being rebound...

lst[:] = []

is rebinding the elements inside the list "lst", and not rebinding the
name "lst". Essentially, once you add any "selector" to the name
(object[...]= or object.xxx=) you are going "inside" the object, and
manipulating (rebinding) what is inside. If the name is used "pure"
(object=), you are rebinding the /name/ to a different object.


Me gets corrected, thanks. Now I need to unroll my mind somewhat back to
figure out when and why I started to believe it sometimes assigns ;)

-- Sergei.

Apr 14 '06 #74
On 2006-04-14, Sergei Organov <os*@javad.com> wrote:
Dennis Lee Bieber <wl*****@ix.netcom.com> writes:
It always means bind... But if the LHS is a mutable object, AND you
have specified a component of that object, it is the component that is
being rebound...

lst[:] = [] [...]
Me gets corrected, thanks. Now I need to unroll my mind somewhat back to
figure out when and why I started to believe it sometimes assigns ;)


I used to think it assigned with things like integers, because if you
write:

a = 5
b = a
b += 1
print a

a is still 5. So it looked like a and b stored values and b got a "copy"
of a's value. But this is the wrong interpretation,

b += 1

is really b = b + 1, and rebinds b.

You can see what's really going on if you use the id() function on a and
b during these operations.

The other reason for the confusion is that I think in Java a variable
either stores a value, in the case of numbers, or a reference in the
case of objects (or a copy-on-write reference, which behaves like a
value, in the case of strings). In Python it's better to think of it as
always a reference, and to think in terms of immutable vs. mutable
objects that are referred to.

If it weren't for the id() function I think the difference between
"variable stores value", "variable stores immutable reference" and
"variable stores copy-on-write reference" would be implementation detail
and never visible to the programmer. That's why it's easy to be
"confused"-- most of the time these interpretations are equivalent, so
it doesn't matter which you work with.
Apr 14 '06 #75
Raymond, I suspect we're not seeing eye to eye on this issue, but I do
appreciate you taking the time and effort. Thank you. My comments follow.

On Thu, 13 Apr 2006
09:34:46 -0700, Raymond Hettinger wrote:
Both the pros and cons
were quipped with abrupt perjoratives so the bullet points could be
stated succinctly and with a bit of levity.
Humour so often doesn't come across in text -- I didn't see the levity you
intended.

"request is inane" --> "A generation of python programmers has found
list clearing to be like other parts of the language that you get used
to very quickly and do not prove to be a problem in practice. The
request is in the same category as others which challenge api choices
made 16 years ago; in particular, the decision to have compact APIs
where the named methods do not duplicate functionality provided by
syntax using operators and keywords. The request is less of a bug
report and more a rejection of Guido's sense of design and his
subsequent experience using his own language."


Of course it isn't a bug report. It's a feature request.

As for Guido's sense of design, in *this particular instance* I think he
got it wrong. That's hardly a rejection of the man's overall design skills.

In any case, as the creator of Python, Guido has never seen the language
with the eyes of a Python beginner. All the more credit to him for
creating a language which is simultaneously friendly to beginners and
powerful for experts. But he isn't superhuman, his experience is not the
only experience. (True, as BDFL, his experience has the final vote, but
that's a whole different kettle of fish.)

A bit of searching on Google finds this issue coming up frequently. It
seems to me that there is a steady stream of Python programmers asking
"where's the list clear method?". Perhaps it isn't a monthly occurrence,
but it is still very common. That surely suggests that, as powerful
as slicing is, people aren't getting the connection between slicing and
emptying a list, and even when they do get it, many dislike it.

Since there is no evidence that these people are universally stupid, it
suggests strongly that the connection is too subtle. Some may protest that
the idiom is in the tutorial, that it is obvious once you know slicing and
del, but the fact is that many people aren't finding it obvious or
self-evident at all -- not even those who have read the tutorial.

Here is another possible solution: have the list.clear method be defined
this way:

def clear(self):
print "Haven't you read the tutorial? Use del self[:] or self[:] = []"

That at least will stop the procession of people asking how to clear a
list, and Fredrik won't have to spend his time telling them to read the
tutorial.

(Hey, if it's good enough for quit and exit... *wink*)

A list.clear method will make deleting items from a list more OO,
consistent with almost everything else you do to lists, and less
procedural. This is especially true if clear() takes an optional index (or
two), allowing sections of the list to be cleared, not just the entire
list.


Don't shoot yourself in the foot here. If you want to advocate
list.clear(), then you're hurting your chances by pushing for it to
take an optional argument. Essentially, this amounts to an
unwillingness to use the del-keyword and to duplicate its functionality
with a named method.


Deleting names from namespaces is conceptually distinct from deleting
components of compound objects like lists, and should be handled
differently: objects know their own contents, and can operate on
themselves, but they don't know what namespace they live in or what
name(s) they are known by. Deleting items from a list should be a case of
"object, operate on yourself", just like remove, append and so on, and
hence should be specified by an object method, not a keyword like del.

So you are right: I am uncomfortable having del do double duty to both
delete names and operate on the internals of compound objects. It feels
wrong to me. If insert were a keyword (as in "insert list[i:j], obj") it
would feel wrong to me too, and for the same reason.

I haven't been using Python for sixteen years, but at six years and
counting I'm not exactly a newbie. At first I accepted the del obj[:]
idiom implicitly -- the whole language was new to me, and it was no more
strange to me than any other Python syntax or idiom. But as I've got more
familiar with Python, the sense of two distinct concepts being
artificially forced into the same syntax has just gotten stronger.

As a pragmatist, I'd be happy to see a bare list.clear() method; that
would at least have the advantages of being easy to find with dir(list)
and accessible with help(). But as a purist, I really think it needs
optional arguments. Make of that what you will.

--
Steven.

Apr 14 '06 #76
Duncan Booth wrote:
Looking in the 'obvious' place in the Tutorial, section 5.1 'More on
Lists' I found in the immediately following section 5.2 'The del
statement':


I read the tutorial 6 years ago, and don't read it regularly. What's in
the tutorial is not really important, what can be easily looked up in
library reference or interctive prompt is.

There is a bit of "elitism" regarding the defense of del lst[:]. Many
python programmers are "casual" programmers (was it Tim Berners-Lee
that explained how great python is for casual users?) who know the
language but don't remember the way everything is done. Of course
someone that uses python 8 hours a day instantly recall lst[:], but a
casual one will more probably launch an ipython prompt and do:

[ipython]|1> l = []
[ipython]|2> l.
l.__add__ l.__getslice__ l.__ne__ l.append
l.__class__ l.__gt__ l.__new__ l.count
l.__contains__ l.__hash__ l.__reduce__ l.extend
l.__delattr__ l.__iadd__ l.__reduce_ex__ l.index
l.__delitem__ l.__imul__ l.__repr__ l.insert
l.__delslice__ l.__init__ l.__reversed__ l.pop
l.__doc__ l.__iter__ l.__rmul__ l.remove
l.__eq__ l.__le__ l.__setattr__ l.reverse
l.__ge__ l.__len__ l.__setitem__ l.sort
l.__getattribute__ l.__lt__ l.__setslice__
l.__getitem__ l.__mul__ l.__str__
[ipython]|2> # wtf?

Apr 14 '06 #77
"Ben C" wrote:
I used to think it assigned with things like integers, because if you
write:

a = 5
b = a
b += 1
print a

a is still 5. So it looked like a and b stored values and b got a "copy"
of a's value. But this is the wrong interpretation,

b += 1

is really b = b + 1, and rebinds b.
almost: "b += obj" is really "b = b.__iadd__(obj)" with "b = b + obj"
as a fallback if __iadd__ isn't supported by "b".
If it weren't for the id() function I think the difference between
"variable stores value", "variable stores immutable reference" and
"variable stores copy-on-write reference" would be implementation
detail and never visible to the programmer.


except when they are:
a = [1, 2, 3]
b = a
b += [4]
a [1, 2, 3, 4] b

[1, 2, 3, 4]

</F>

Apr 15 '06 #78

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Mike | last post by:
How do I extract a list of lists from a user defined function and print the results as strings for each list?
5
by: sam | last post by:
Hi, The following code produced a core-dump: PropertyParser::PropertyParser(list<HashMap> &p_list) { l_conf_data.clear(); cout << "beginning copy.. size: " << p_list.size() << endl;...
2
by: Water Cooler v2 | last post by:
What am I missing here. I bind a drop-down list in ASP.NET placed on a web form to a DataReader. The binding is done at run-time and not at design time. Here's the code I write to bind the list: ...
10
by: pamelafluente | last post by:
Hi I have a sorted list with several thousands items. In my case, but this is not important, objects are stored only in Keys, Values are all Nothing. Several of the stored objects (might be a...
3
by: =?Utf-8?B?THVib21pcg==?= | last post by:
Hi, I am wondering how I could clear the invokation list of delegates. I tried the following: //make a chain MyDel += SomeDel; // Clear the chain
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.