473,746 Members | 2,211 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 #1
65 4228
Steven Watanabe wrote:
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?


No. Consider this simple example:

class Foo(object):
def __init__(self, all_my_thingies ):
self.all_my_thi ngies = all_my_thingies
things = [1,2,3,4,5]

f = Foo(things)

things = [] # I've been robbed

print f.all_my_thingi es # or not?
The reason is that l = [] just rebinds a new object (a list, but it could be
anything) to a name, while l[:] = [] will alter the object _referred_ to by
l. That is a HUGE difference!
Diez

Jan 31 '06 #2
Steven Watanabe wrote:
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.


The solution (1) and (2) clear the content of the list (replace the
content of the list by an empty list for (1), or delete the content of
the list for (2) while the solution (3) creates a new list and binds the
old name to the new list. This means that you don't actually modify
(clear) the initial list.

Just try it out:
a = range(10)
a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = a
b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] c = a
c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a.append(10) # assert that a, b and c point to the same list
a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = []
b [] a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] del c[:]
c [] a []


Here we can see that using method (3) on b didn't modify the content of
a (even though we asserted that they were the same list).
Using method (2) on c, the other hand, did modify the content of a.

This is because method (3) on b actually created a new list and bound
"b" (as a name) to that new list, without modifying the list "b" used to
be bound to (which is the one "a" and "c" are still bound to).
Jan 31 '06 #3
Diez B. Roggisch:
The reason is that l = [] just rebinds a new object (a list, but it could be
anything) to a name, while l[:] = [] will alter the object _referred_ to by
l. That is a HUGE difference!


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).

Bye,
bearophile

Jan 31 '06 #4
Steven Watanabe wrote:
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?


I'm wondering why there is no 'clear' for lists. It feels like a common
operation for mutable containers. :-/
Will McGugan

Feb 6 '06 #5
Will McGugan wrote:
Steven Watanabe wrote:
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?

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!

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 6 '06 #6
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

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.
--
Steven.

Feb 6 '06 #7
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?

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.

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Feb 6 '06 #8
Steven D'Aprano 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"...

Feb 6 '06 #9
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.

(del doesn't work on dictionaries)

</F>

Feb 6 '06 #10

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

Similar topics

21
2118
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
1294
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
1354
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
1124
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
2692
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
1680
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
3503
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
1294
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
1445
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
8970
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
8796
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
9348
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...
1
9280
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8221
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...
1
6766
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6057
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
4829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2761
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.