0

I want to make a list of lists in python. I am initializing this list like:

n = 3
adj = [[]]*n

So now when I print adj, I get:

[[], [], []]

...which is fine.

Now, I want to append values to a particular list (one particular index). I have done this:

adj[0].append(1)

Hence, my expected output is:

[[1], [], []]

However the output is:

[[1], [1], [1]]

I can't seem to understand why this is so. Probably I am not understanding something about how Python's lists work, or am making an utterly silly mistake. Any help would be greatly appreciated.

Additionally, I would really appreciate a suggestion as to how I can get my desired output.

Ideone link here.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Debanik Dawn
  • 797
  • 5
  • 28

1 Answers1

2

This behavior is expected in Python. Using the * operator in this context creates references to the list() objects, which means that when you modify one such object (like you did with your append() operation), you modify all of the references to that object.

To get your desired output, I would recommend using a loop to create lists that aren't aliases of each other:

>>> adj = [[] for i in range(3)]
>>> adj[0].append(1)
>>> [[1], [], []]
Daniel
  • 2,345
  • 4
  • 19
  • 36