4

I create 4 identical lists of lists L1, L2, L3, L4

>>> L0 = [[1]]
>>> L1 = [[1],[1]]
>>> L2 = [[1] for i in range(2)]
>>> L3 = L0 + L0
>>> L4 = [[1]] * 2

>>> L1
[[1], [1]]
>>> L2
[[1], [1]]
>>> L3
[[1], [1]]
>>> L4
[[1], [1]]

>>> L1 == L2 == L3 == L4
True

And apply list.append() to the first element in each

>>> L1[0].append(2) 
>>> L2[0].append(2)
>>> L3[0].append(2)
>>> L4[0].append(2)

with result

>>> L1
[[1, 2], [1]]
>>> L2
[[1, 2], [1]]
>>> L3
[[1, 2], [1, 2]]
>>> L4
[[1, 2], [1, 2]]

Can somebody please explain the output for L3 and L4?

2 Answers 2

1

In all of these cases, the lists consist of references to other lists within them. In the case of L3 and L4 they are lists which consist of references to a single other list (L0 for L3 and for L4 a single on-the-fly list [1]).

This is what the [...]*2 syntax means -- make two references to the entry found inside the base list.

When you append, you modify the referred-to list, in all of its locations.

In other words, when you modify L3[0], you are modifying a thing that L3[1] also refers to, so later when you query to see what L3[1] looks like, it reflects the now-modified version of what it has been referring to all along.

Equality between lists is defined in terms of equality of the ordered elements they contain. This applies recursively to lists of lists, and so on. So at base, your equality check is a question about the integers inside the lists, and not about the actual list object instances:

In [24]: x = [[1]]

In [25]: y = [[1]]

In [26]: x[0]
Out[26]: [1]

In [27]: y[0]
Out[27]: [1]

In [28]: x[0] == y[0]
Out[28]: True

In [29]: id(x[0])
Out[29]: 140728515456032

In [30]: id(y[0])
Out[30]: 140728514976728
Sign up to request clarification or add additional context in comments.

Comments

1

Because L3 and L4 are actually references so when you append to L3[0] and L4[0], you actually modify what they refer to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.