473,322 Members | 1,911 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,322 software developers and data experts.

stupid/style/list question

I was wondering...
To flush a list it is better doing "del mylist[:]" or "mylist = []"?
Is there a preferred way? If yes, why?
Jan 8 '08 #1
7 968
Giampaolo Rodola' wrote:
To flush a list it is better doing "del mylist[:]" or "mylist = []"?
Is there a preferred way? If yes, why?
The latter creates a new list object, the former modifies an existing
list in place.

The latter is shorter, reads better, and is probably a bit faster in
most cases.

The former should be used when it's important to clear a specific list
object (e.g. if there are multiple references to the list).

</F>

Jan 8 '08 #2
To flush a list it is better doing "del mylist[:]" or "mylist = []"?
Is there a preferred way? If yes, why?
It depends on what you want. The former modifies the list
in-place while the latter just reassigns the name "mylist" to
point to a new list within the local scope as demonstrated by this:

def d1(mylist):
"Delete in place"
del mylist[:]

def d2(mylist):
"Just reassign"
mylist = []

for test in [d1,d2]:
input = [1,2,3]
print 'Before:', input
print test.__doc__
test(input)
print 'After:', input
print

As performance goes, you'd have to test it, but I suspect it's
not a glaring difference, and would suspect that the latter is a
bit faster.
-tkc
Jan 8 '08 #3
On 8 Gen, 16:45, Fredrik Lundh <fred...@pythonware.comwrote:
Giampaolo Rodola' wrote:
To flush a list it is better doing "del mylist[:]" or "mylist = []"?
Is there a preferred way? If yes, why?

The latter creates a new list object, the former modifies an existing
list in place.

The latter is shorter, reads better, and is probably a bit faster in
most cases.

The former should be used when it's important to clear a specific list
object (e.g. if there are multiple references to the list).

</F>
I'm going to use the latter one, thanks.
Jan 8 '08 #4
On Jan 8, 7:34 am, "Giampaolo Rodola'" <gne...@gmail.comwrote:
I was wondering...
To flush a list it is better doing "del mylist[:]" or "mylist = []"?
Is there a preferred way? If yes, why?

To empty an existing list without replacing it, the choices
are "del mylist[:]" and "mylist[:] = []". Of the two, I
prefer the former because it reads more explicity (delete
all of the items from the list"). In terms of performance,
they are basically the same.

To replace a list, "mylist = []" is the way to go. This is
an affirmative statement that you are creating a new list.

Raymond
Jan 8 '08 #5
Fredrik Lundh <fr*****@pythonware.comwrote:
Giampaolo Rodola' wrote:
>To flush a list it is better doing "del mylist[:]" or "mylist = []"?
Is there a preferred way? If yes, why?

The latter creates a new list object, the former modifies an existing
list in place.

The latter is shorter, reads better, and is probably a bit faster in
most cases.

The former should be used when it's important to clear a specific list
object (e.g. if there are multiple references to the list).
I tried to measure this with timeit, and it looks like the 'del' is
actually quite a bit faster (which I find suprising).

C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)"
10000 loops, best of 3: 81.1 usec per loop

C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)"
"del mylist[:]"
10000 loops, best of 3: 61.7 usec per loop

C:\Python25\Lib>timeit.py -s "lista=range(10000)" "mylist=list(lista)"
"mylist=[]"
10000 loops, best of 3: 80.9 usec per loop
In the first test the local variable 'mylist' is simply allowed to go
out of scope, so the list is destroyed as its reference count drops to
0.

In the third case again the list is destroyed when no longer referenced,
but an empty list is also created and destroyed. Evidently the empty
list takes virtually no time to process compared with the long list.

The second case clears the list before destroying it, and appears to be
significantly faster.

Increasing the list length by a factor of 10 and it becomes clear that
not only is #2 always fastest, but #3 always comes in second. Only when
the lists are quite short (e.g. 10 elements) does #1 win (and even at 10
elements #2 beats #3).

Unless I've missed something, it looks like there may be an avoidable
bottleneck in the list code: whatever the slice delete is doing should
also be done by the deletion code (at least if the list is longer than
some minimum length).

The most obvious thing I can see is that list_dealloc:

if (op->ob_item != NULL) {
/* Do it backwards, for Christian Tismer.
There's a simple test case where somehow this reduces
thrashing when a *very* large list is created and
immediately deleted. */
i = Py_Size(op);
while (--i >= 0) {
Py_XDECREF(op->ob_item[i]);
}
PyMem_FREE(op->ob_item);
}
would be better written as a copy of (or even call to) list_clear which
picks up op->ob_item once instead of every time through the loop.

Jan 9 '08 #6
Duncan Booth:
I tried to measure this with timeit, and it looks like the 'del' is
actually quite a bit faster (which I find suprising).
Yes, it was usually faster in my benchmarks too. Something similar is
true for dicts too. I think such timings are influenced a lot by the
garbage collector.

Bye,
bearophile
Jan 9 '08 #7
be************@lycos.com wrote:
Duncan Booth:
>I tried to measure this with timeit, and it looks like the 'del' is
actually quite a bit faster (which I find suprising).

Yes, it was usually faster in my benchmarks too. Something similar is
true for dicts too. I think such timings are influenced a lot by the
garbage collector.
That may come into it, but I made the obvious change I mentioned (to avoid
dereferncing a pointer every time through the loop) and got about an 8%
speed-up on my test. I don't think that explains all of the speed
difference though, so the garbage collector may come into it too: I'll see
if I can do some more experimentation before submitting a patch.

Jan 9 '08 #8

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

Similar topics

8
by: sebb | last post by:
I'm kind of newbie to programming, but I thought of something and I want some opinions on that. It's about a new instruction block to do some cycles. I thought about that because it's not very...
6
by: Haines Brown | last post by:
I find that when I use list-style-image with galeon or mozilla, padding is inserted between the symbol image and the following list text, while under IE 5.0 it seems to be inserted before the image...
16
by: Justin Hoffman | last post by:
This is a question concerning query optimisation. Sorry if it's a bit long, but thanks to anyone who has the patience to help - This is my first post here... If I have two tables:...
21
by: Michael Bierman | last post by:
Please forgive the simplicy of this question. I have the following code which attempts to determine the color of some text and set other text to match that color. It works fine in Firefox, but does...
36
by: Hoopster | last post by:
Hello, I know nothing about C++ but want to get started. Is there any good free C++ program that I can try to see if I like programming? I also need a good free compiler. I don't want to...
2
by: Lampa Dario | last post by:
Hi, where is this stupid error in this program? When I execute it, i receive a segmentation fault error. #include <stdio.h> int main(int argc, char *argv, char *env) { int i=0; int l=0; int...
14
by: UJ | last post by:
What's the easiest way (without setting up a style sheet) to set the font for an area of text. I need to be able to specify the exact font and font size - not the 1-7 numbers IE uses. I want to be...
2
by: Mike - EMAIL IGNORED | last post by:
I have: <ol style="list-style-type: lower-alpha"> <li>Great Innovation <li>Greater Innovation </ol> Which results in: a. Great Innovation
6
by: MatthewS | last post by:
I've seen the question raised several times here, but apparently never answered. Since PyInstance_Check returns False for new-style class instances, is there a standard procedure for testing this...
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
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
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: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
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.