semantics of [:]
Dave Angel
davea at ieee.org
Fri Nov 20 12:29:09 EST 2009
Diez B. Roggisch wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">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
>
>
While Diez is correct, I think it could be less confusing. So I'll try
to put it clearer. If it's not, sorry.
(2) binds an empty list to c, and immediately rebinds it to a new list,
copied from a.. So the c=[] line is totally irrelevant, unless there's
some other code in between.
(3) again binds an empty list to d, but this is important, because the
following line wouldn't be legal if there weren't already a list. The
only time this has a different practical effect from the other two is if
there's some other code between the two lines. If that other code binds
something to the same object then it definitely matters.
I'd say (1) is the preferable form, as no visible object is in an
in-between state. The copy is built anonymously, then bound only when
it has its full value.
DaveA
More information about the Python-list
mailing list