semantics of [:]

Diez B. Roggisch deets at nospam.web.de
Fri Nov 20 11:21:49 EST 2009


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.

Of course, in your concrete example, the looks of it are the same. The 
distinction is crucial in larger contexts.

Diez



More information about the Python-list mailing list