semantics of [:]

Esmail ebonak at hotmail.com
Fri Nov 20 13:04:39 EST 2009


Diez B. Roggisch wrote:
> Esmail schrieb:
>> Could someone help confirm/clarify the semantics of the [:] operator
>> in Python?
>>
>> a = range(51,55)
>>
>> ############# 1 ##################
>> b = a[:] # b receives a copy of a, but they are independent
>  >
>>
>>
>> # The following two are equivalent
>> ############# 2 ##################
>> c = []
>> c = a[:] # c receives a copy of a, but they are independent
> 
> No, the both above are equivalent. Both just bind a name (b or c) to a 
> list. This list is in both cases a shallow copy of a.
> 
>>
>>
>> ############# 3 ##################
>> d = []
>> d[:] = a # d receives a copy of a, but they are independent
> 
> 
> This is a totally different beast. It modifies d in place, no rebinding 
> a name. So whover had a refernce to d before, now has a changed object, 

I follow all of this up to here, the next sentence is giving me pause

> whereas in the two cases above, the original lists aren't touched.

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

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

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



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

Thanks again.




More information about the Python-list mailing list