semantics of [:]

Diez B. Roggisch deets at nospam.web.de
Fri Nov 20 18:42:00 EST 2009


Esmail schrieb:
> 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?

None of your operations changes a. But I talked about the lists you 
bound b and c to before. Those aren't changed as well - they simply are 
not pointed to anymore. In your example, that means the will be 
garbage-collected, in other scenarios, such as this, the stay:

a = []
foo = []
bar = foo
assert bar is foo
bar = a[:]
assert bar is not foo

Diez



More information about the Python-list mailing list