On 17/07/13 16:48, Jim Mooney wrote:
On 16 July 2013 20:42, Steven D'Aprano <st...@pearwood.info> wrote:

Here's a question for you, to test your Python knowledge:

What knowledge? I've been fooling around in this awful AZ heatwave and
only got to chap 5 in the Lutz book. ;')

Assuming that some_list is already a list, what's the difference between
these two lines, and under what circumstances why would you want to use the
second one?

some_list = []
some_list[:] = []

However, fooling around helps, so I'd say:

p = [1,2,3]
id(p)
34586456
p[:] = []
id(p)
34586456
p = []
id(p)
34586752

The slice will pass an "is" test, the equal will not.

Correct, but you may not have worked out the consequences that follow from that.

[Aside: ID numbers may be reused. So it is possible, although unlikely, that id(p) will remain the 
same by chance after p = []. That can't happen with Jython or IronPython, as they never re-use IDs, 
and I don't think it can happen for CPython, but it would be permitted behaviour for Python 
implementations. So if you wish to test for "is", you should actually use "is", 
and not just eyeball the ID.]

p = [1, 2, 3]
q = p
# confirm that q is not a copy of p, but they are
# two names for the same object
assert p is q

p[:] = []
assert p is q  # p and q remain the same object
assert q == []

p = q = [1, 2, 3]
p = []
assert p is not q  # p is a new list, q is still the old one


This is not just of theoretical interest. Sometimes you will have a function 
that accepts a list argument, and you might wish to clear the list. Depending 
on how you do so, the change may or may not propagate outwards to the caller:


mylist = [1, 2, 3, 4]
process(mylist)
print mylist

What gets printed depends on what process() does.

If process() clears the list using the slice version, then it will be cleared 
on the outside too. But if instead it assigns a new empty list to it, then the 
old list object remains untouched and mylist will not change.



No fair making me think.This is as bad as being back in school.

Heh :-)


--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to