0

Here's my code:

res = [[]] * 4
res[0]  = ['0', '1']
res[1].extend(['1' + x for x in res[0]])

After each line, res is equal to:

[[], [], [], []]
[['0', '1'], [], [], []]
[['0', '1'], ['10', '11'], ['10', '11'], ['10', '11']]

Why is res not equal to [['0', '1'], ['10', '11'], [], []] after line 3? How could I extend res[1] without also extending res[2] and res[3]?

  • `[[]] * 4` doesn't do what you think it does. You create a list containing four list-references, effectively. All inner lists will be referring to the same underlying list in memory, and any change you apply to ANY of them will be reflected in the other references. You're looking for `res = [[] for _ in range(4)]` – Paul M. Apr 12 '21 at 20:02
  • Yes, this answers my question. Thanks for your help, Paul M and jasonharper. – Daniel Conroy Apr 12 '21 at 20:08

2 Answers2

1

Items in list are references to objects.

[[]] is a list consist of one reference to a list.
[[]] * 4 make new list that consist of the same reference four times.

Use the following to create a list of four different references to their own lists.

res = [[] for _ in range(4)]
Aaron
  • 1,255
  • 1
  • 9
  • 12
0

The basics of programming is that there are two parts to memory, the values you want to hold, and the locations those values are stored. In general, the location of something in memory is called a "pointer". Some languages are very clear about pointers and their values, like in C. But in python, most of that information is hidden from view, and only shows up sometimes.

What is happening with

x = [[]]*4

is that python is creating an object [] and then placing the pointer to that object in another list. It then sees the 4 and copies that pointer 4 times. Hence, your list of 4 lists, is really a list of 1 list that are each pointing to the same object. Hence, we you edit the first list, and then re-print x, it displays that list edited 4 times.

x[0].append(7)
print(x)

Python has a built-in function that returns the pointer to an object, id(). This can be used to find out if you are looking at 4 different lists or the same list 4 times.

print(id(x[0]))
print(id(x[1]))

This shows that entry 0 and entry 1 are the exact same object. Hope that clarifies what is happening a bit.

Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15