List semantics [was Re: Slices time complexity]

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed May 20 03:23:54 EDT 2015


On Wednesday 20 May 2015 16:23, Rustom Mody wrote:

> I dont like teaching this. viz that in python
> x = [[1,2],[1,2]]
> is equal to y defined as
> z = [1,2]
> y = [z,z]
> And although they are equal as in '==' they are not equal as in behavior,
> memory usage etc, a fact that can only be elucidated by box-n-arrow
> diagrams.

"Only"? 

You don't need diagrams to explain the differences between the two.


Code snippet 1:

    x = [[1,2],[1,2]]

creates a list bound to the name "x", containing a list containing ints 1 
and 2, and a second independent list also containing ints 1 and 2. Here 
there are three lists in total, and one named variable.

Code snippet 2:

    z = [1,2]
    y = [z, z]

creates a list bound to the name "z", ints 1 and 2; then it creates a second 
list, bound to name "y", containing the first list "z" twice. Here there are 
two distinct lists in total, and two named variables. The two items inside y 
are the same list, namely z, not distinct lists.


A diagram may help, especially for more complicated situations, or for the 
slow of thinking, but it's not essential. There's no need to talk about the 
implementation, pointers or memory addresses so long as you stick to 
Python's object-based language model.


-- 
Steve




More information about the Python-list mailing list