473,670 Members | 2,333 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about idioms for clearing a list

I know that the standard idioms for clearing a list are:

(1) mylist[:] = []
(2) del mylist[:]

I guess I'm not in the "slicing frame of mind", as someone put it, but
can someone explain what the difference is between these and:

(3) mylist = []

Why are (1) and (2) preferred? I think the first two are changing the
list in-place, but why is that better? Isn't the end result the same?

Thanks in advance.
--
Steven.
Jan 31 '06
65 4196
Fredrik Lundh wrote:
(del doesn't work on dictionaries)


.... or rather [:] doesn't work on dictionaries ...

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
d={'a':1, 'b':2, 'c':3}
print d {'a': 1, 'c': 3, 'b': 2} del d['b']
print d {'a': 1, 'c': 3} del d[:] Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unhashable type


Regards. Mel.
Feb 6 '06 #11
On Mon, 06 Feb 2006 09:39:32 -0500, Dan Sommers wrote:
On Tue, 07 Feb 2006 01:01:43 +1100,
Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
On Mon, 06 Feb 2006 13:35:10 +0000, Steve Holden wrote:
I'm wondering why there is no 'clear' for lists. It feels like a common
operation for mutable containers. :-/

Because it's just as easy to create and assign a new empty list (and
have the old unused one garbage collected).

l = []

is all you need!
Not so. If that logic were correct, then dicts wouldn't need a clear
method either, because you could just assign a new empty dict with d = {}.

But your own sentence tells us why this is not sufficient: because you
aren't emptying the list, you are reassigning (rebinding) the name. The
old list still exists, and there is no guarantee that it will be garbage
collected, because there is no guarantee that it isn't in use somewhere
else:

L = [0,1,2]
D = {"key": L}
L = [] # rebinds the name L, but the list instance still exists


That is a red herring. Consider this:

L = [object(), object()]
O = L[1]
L = [] # or insert your favorite list-clearing/emptying statement here

What damage is done now that O is still referring to one of the items
that used to be in L?


What relevance is this? If there is one and only one reference to the list
L, then it will be garbage collected when L is rebound. I never denied
that. I pointed out that, in the general case, you may have multiple
references to the list (not all of which are bound to names), and
rebinding the name L will NOT have the side-effect of clearing the list.

The trouble begins when references to "the list to which L refers" end
up somewhere else. Then we have to wonder if rebinding L will leave
some other block of code with an outdated list.


Precisely, just as my example shows.
--
Steven.

Feb 6 '06 #12
Fredrik Lundh wrote:
Peter Hansen wrote:

Perhaps it is arguable that there is no need for a clear method because
L[:] = [] is so easy to do. Personally, while I agree that it is easy, it
is hardly intuitive or obvious, and I too would prefer an explicit clear
method for mutable sequences.


Possibly another case where "patches are welcome"...

so we can have three ways to do the same thing? the right way to
nuke a sequence is to do "del L[:]". this is explained in Python 101.


The Zen isn't "only one way to do it". If it were, we
wouldn't need iterators, list comps or for loops,
because they can all be handled with a while loop (at
various costs of efficiency, clarity or obviousness).

del L[:] works, but unless you are Dutch, it fails the
obviousness test. It also fails the introspection test:
neither dir(list) nor help(list) make it easy to
discover how to empty a list. In my opinion, the
primary advantage for a clear() method would be that it
is self-documenting.

--
Steven.

Feb 7 '06 #13
Steven D'Aprano wrote:
so we can have three ways to do the same thing? the right way to
nuke a sequence is to do "del L[:]". this is explained in Python 101.
The Zen isn't "only one way to do it". If it were, we
wouldn't need iterators, list comps or for loops,
because they can all be handled with a while loop (at
various costs of efficiency, clarity or obviousness).

del L[:] works, but unless you are Dutch, it fails the
obviousness test.


unless you read some documentation, that is. del on sequences
and mappings is a pretty fundamental part of Python. so are slicings.

both are things that you're likely to need and learn long before you
end up in situation where you need to be able to clear an aliased
sequence.
It also fails the introspection test:


so does "print L".

</F>

Feb 7 '06 #14
[Steven D'Aprano]
The Zen isn't "only one way to do it". If it were, we
wouldn't need iterators, list comps or for loops,
because they can all be handled with a while loop (at
various costs of efficiency, clarity or obviousness).

del L[:] works, but unless you are Dutch, it fails the
obviousness test.

[Fredrik Lundh] unless you read some documentation, that is. del on sequences
and mappings is a pretty fundamental part of Python. so are slicings.

both are things that you're likely to need and learn long before you
end up in situation where you need to be able to clear an aliased
sequence.


Fred is exactly correct. Slicing is absolutely basic to Python.
Accordingly, it gets covered right at the beginning of the tutorial
(section 3.1). Likewise, the del keyword is fundamental -- if you
can't get, set, and del, then you need to go back to collections
school.

Also specious is the suggestion that dir(L) or help(L) is useless. The
entries for the __delitem__ and __delslice__ methods are no more hidden
than for __getitem__ or __add__. The help entry goes a step further
and shows the translation to del x[y] and del x[i:j].

While the sentiment behind the list.clear() suggestion is noble, it is
an exercise in futility to design a language around the presumption
that other programmers are incapable of learning the basics of the
language.

There was a pithy Tim Peters quotation to the effect that he was
unpersuaded by language proposals predicated on some hypothetical
average programmer not being smart enough to understand something that
the rest of us find to be basic.
Raymond Hettinger

Feb 7 '06 #15
[be************@ lycos.com]
In my programs I have seen that there is another practical difference
between version 1 and 3:
(1) mylist[:] = []
(3) mylist = []
If you create a big mylist again and again many times, the version 1
uses the memory more efficiently (probably less work for the garbage
collector), and the program can be (quite) faster (this is true in some
implementations different from CPython too).


There should be almost no difference in runtime between the two. The
underlying CPython implementation caches list objects and is usually
able to create the new list without any calls to the memory allocator.
Likewise, garbage collection performs the same for both -- any objects
left with no references are immediately freed and any with only
circular references get freed when the collector runs.

The speed-up you observed likely occured with different code. For
instance, given a large list, you can typically update or replace
individual elements faster than you can build-up a new list:

L = [0] * 1000 # starting list
for i in xrange(len(L)):
L[i] += 1

beats:

L = [0] * 1000 # starting list
L = [L[i]+1 for i in xrange(len(L))]
Raymond

Feb 7 '06 #16
Raymond Hettinger wrote:
[Steven D'Aprano]
The Zen isn't "only one way to do it". If it were, we
wouldn't need iterators, list comps or for loops,
because they can all be handled with a while loop (at
various costs of efficiency, clarity or obviousness).

del L[:] works, but unless you are Dutch, it fails the
obviousness test.

[Fredrik Lundh]
unless you read some documentation, that is. del on sequences
and mappings is a pretty fundamental part of Python. so are slicings.

both are things that you're likely to need and learn long before you
end up in situation where you need to be able to clear an aliased
sequence.


Fred is exactly correct. Slicing is absolutely basic to Python.
Accordingly, it gets covered right at the beginning of the tutorial
(section 3.1).


Yes, right after UTF encoding details, complex numbers, and various
mentions of shell scripts. I don't want to criticise the hard work that
went into making the tutorial but let's not pretend it's the epitome of
documentation or even necessary the most obvious reference for users.
Likewise, the del keyword is fundamental -- if you
can't get, set, and del, then you need to go back to collections
school.


I have hardly used the del keyword in several years of coding in
Python. Why should it magically spring to mind in this occasion?
Similarly I hardly ever find myself using slices, never mind in a
mutable context.

del L[:] is not obvious, especially given the existence of clear() in
dictionaries. I'm not necessarily requesting a clear() method, but I am
requesting a little more understanding towards those who expected one.
The list interface is full of redundant convenience methods, so one
more would hardly be a surprise or an unreasonable thing for people to
expect. Again we unfortunately have a bit of an attitude problem
towards anyone posting here that doesn't know whatever the experts
think is obvious.

--
Ben Sizer

Feb 7 '06 #17
Raymond Hettinger wrote:
[Steven D'Aprano] [...]
While the sentiment behind the list.clear() suggestion is noble, it is
an exercise in futility to design a language around the presumption
that other programmers are incapable of learning the basics of the
language.
+1 QOTW
There was a pithy Tim Peters quotation to the effect that he was
unpersuaded by language proposals predicated on some hypothetical
average programmer not being smart enough to understand something that
the rest of us find to be basic.

Well, for those who can't find it you just provided a fairly pithy
Raymond Hettinger quote :-)

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Feb 7 '06 #18
Raymond Hettinger wrote:

There was a pithy Tim Peters quotation to the effect that he was
unpersuaded by language proposals predicated on some hypothetical
average programmer not being smart enough to understand something that
the rest of us find to be basic.


Peters pithy ;)

As someone coming to Python as a well less than the average programmer,
I agree wholeheartedly with Mr. Peters.

My ability to grok Python to any extent, from that starting point, was
based on an understanding that it was my responsibility to come to
Python, not it to me. And concerted, almost obsessive effort, And time.

OTOH - because of exactly these factors - I have actively resented and
resisted promulgation of the Python is Easy meme.

Pity that this stance has separated me from a sense of belonging to the
community, which seems to so highly value that meme.

Art
Feb 7 '06 #19
Arthur wrote:

My ability to grok Python to any extent, from that starting point, was
based on an understanding that it was my responsibility to come to
Python, not it to me. And concerted, almost obsessive effort, And time.

OTOH - because of exactly these factors - I have actively resented and
resisted promulgation of the Python is Easy meme.

Pity that this stance has separated me from a sense of belonging to the
community, which seems to so highly value that meme.


What Python *is*, to me, is a game worth playing. Not something I come
across all that often. And easy games, almost invariably, are not.

Art
Feb 7 '06 #20

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

Similar topics

21
2110
by: JustSomeGuy | last post by:
When you iterate through a list of objects in a list. list<object> mylist; list<object>::const_iterator iter; object ob; for (iter=mylist.begin(); iter != mylist.end(); ++iter) { ob = *iter; ob.value = 10;
4
1292
by: lallous | last post by:
Hello Given this: list<mystruct_t> lst; lst.push_back(item1); lst.push_back(item2); lst.push_back(item3);
2
1347
by: Brian | last post by:
Hi I'm working on a site that has a form on it to do an advanced search on a database, in the form are 2 list (<select>) Both these list have items in them, what I want to do is if an items it selected from list A then it sets list B value to null and of cause the other way round. The reason is I need to make sure that when the form is submitted I only pass an item from either list A or B not both is I do a test on each variable to...
2
1119
by: Wong CS | last post by:
Dear all, i hav a problem when i compile my web application... this is the SQL query i used to insert my data into database. string InsertBuyerDetail = @"INSERT INTO Buyer (Buy_Login, Buy_Password, Buy_Country) Values ('"+userID.Text+"', '"+pw1.Text+"', '"+Buyer_country+"')"; it work fine if i juz do for Buy_Login and Buy_Password but not in
7
2685
by: situ | last post by:
Hi, we i get a snapshot for lock on db i'm getting LOCK_LIST_IN_USE =5560 and my LOCKLIST parameter = 50, is it ok for OLTP database or do i have to do any tuning here. thanks sridhar
3
1670
by: eric dexter | last post by:
I apologise if I annoy in advance. This is very close to what I want but I need to return a list of instr_numbers not just one and it seems that no matter what I do I just get two items from a split and not the three I need.. What I am getting not is just the last instr number and the comment (Maybe a bug in my re or in the split) thanks in advance for the help. The .csd text file that I am using to test this is available if needed at...
2
3495
by: Antony Clements | last post by:
i have written a program that incorporates the following code. Private Sub Dir1_Change() 'changes the folder and displays each file in the folder On Error Resume Next File1.Path = Dir1.Path RaiseEvent DirectoryChanged(Dir1.Path) File1.Selected(0) = True frmMain2.lblFileIn.Caption = Dir1.Path frmMain2.lblFileOut.Caption = Dir1.Path
9
1287
by: Thomas Ploch | last post by:
Hello fellow pythonists, I have a question concerning posting code on this list. I want to post source code of a module, which is a homework for university (yes yes, I know, please read on...). It is a web crawler (which I will *never* let out into the wide world) which uses regular expressions (and yes, I know, thats not good, too). I have finished it (as far as I can), but since I need a good mark to
2
1441
by: thungmail | last post by:
/* The program read several messages from and store them in a singly linked list */ typedef struct message { int messageId; char * messageText; struct message * next; } message; #include <stdio.h>
0
8471
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8388
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8907
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8817
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7423
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5687
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4396
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2804
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2046
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.