semantics of [:]

Tim Chase python.list at tim.thechases.com
Fri Nov 20 12:17:54 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, 
> whereas in the two cases above, the original lists aren't touched.

To demonstrate what Diez is saying:

   a = range(51,55)
   d = []
   x = d
   d[:] = a
   print x  #hey, I didn't change x...oh, yeah

-tkc












More information about the Python-list mailing list