[Tutor] Nested use of replication operator on lists

Danny Yoo dyoo at hashcollision.org
Fri May 25 01:39:17 EDT 2018


Each value in Python has an associated numeric address associated to it.
We can probe for it:

      https://docs.python.org/3/library/functions.html#id

For example:

#########################
>>> x = [1, 2, 3]
>>> y = x[:]
>>> id(x)
139718082542336
>>> id(y)
139718082556776
#########################

Here, we create a list and point the name 'x' to it.  We point another
name, 'y', to a slice of the first list.  Slicing creates a new list.

Let's make one more name:

#########################
>>> z = x
>>> id(z)
139718082542336
#########################

Note that the numeric id() that we get from 'z' is the same number as the
id() we get from 'x'.  These indicate that both names are referring to the
identical list value.


Identity matters because some values can be changed, or mutated.  It means
that two values can start looking the same, like the two lists that we
created:

#########################
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
#########################

but after a mutation:

##########################
>>> x.append('four')
>>> x
[1, 2, 3, 'four']
>>> y
[1, 2, 3]
##########################

we can see that they are now different.


If we try using 'z', we see:

##########################
>>> z
[1, 2, 3, 'four']
##########################


and that squares with what we said earlier: we gave the list we see here
two names: 'x' and 'z'.  But it's the same list.


To come to your example, to get an intuition of what's happening, try
applying id() on individual elements of the list, to probe which ones are
unique and which ones are the same.  You can also use a graphical tool like
pythontutor.com.  Take a look:  https://goo.gl/HBLTw9


A slight revision to the scenario might make things a little clearer.  Try:

##########################
nested_lists = [['a'], ['b']] * 2
first_element = nested_lists[0]
second_element = nested_lists[1]

first_element.append('c')
second_element.append('d')
##########################

Visualization: https://goo.gl/k4TLvi


See if the graphical view squares away with your internal mental model.
Please feel free to ask questions.


More information about the Tutor mailing list