semantics of [:]
Ethan Furman
ethan at stoneleaf.us
Fri Nov 20 14:22:58 EST 2009
Dave Angel wrote:
> Esmail 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
>>
>> 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).
>>
> (1) is most appropriate in that case. In fact, unless there is other
> code mixed in between, it's always the most appropriate.
Be aware: this is only a shallow copy -- if your copied list contains
mutable objects that you mutate, those changes *will* show up in the
original list.
Shallow copies are useful when, for example, you won't be mutating
objects in the copied list but are adding, removing, or reordering the
copied list.
Hope this helps.
~Ethan~
More information about the Python-list
mailing list