semantics of [:]

Stephen Hansen apt.shansen at gmail.com
Fri Nov 20 13:40:02 EST 2009


>
> The original list 'a', isn't changed in any of these cases right? And
> modifying b, c or d would not change 'a' either - or am I not understanding
> this correctly?
>
> ## 1 ##
>
> creates a new list and copies all elements from a to b
>
>
Yes.


> ## 2 ##
>
> take an already existing list (empty) and copies all elements from a to
> it (no data is lost by c since c was empty to start out with)
>
>
No. The 'already existing list' is simply completely discarded. You're
creating it on one line, then destroying it. A brand new list is being
created and returned and bound to the same name as the already existing
list.


> ## 3 ##
>
> d is a list, and all of its contents (if it had any) would be
> filled with that of a .. but changes to a still are not reflected in d
> .. this is confusing...
>


Not exactly, if I understand you correctly. D is a list, but its contents
(if it had any) would be completely replaced. Any previous content would be
gone, and it would now contain a copy of a.


> Semi-aside, if I wanted to make local copy of a list sent to me as a
> parameter, which of these is the most appropriate to use (I don't want
> changes to change the original list sent).
>


my_copy = original[:]

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091120/f91e2236/attachment.html>


More information about the Python-list mailing list