0

I feel like I'm either missing something really stupid on this. I have the following code:

graph = [[]] * 10
for i in range(2):
  print(graph)
  graph[0].append(1)
  print(graph) 

it outputs

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

Why at each iteration is graph[0].append(1) updating every sublist in graph? Shouldn't it just be adding 1 to the first sublist? (graph[0]). This is happening on Leetcode by the way, not sure if it could be speicifc to that.

Eric Hasegawa
  • 169
  • 1
  • 14
  • Never write `graph = [[]] * 10` unless you absolutely understand what it means. Write `graph = [[] for _ in range(10)]` instead. – Stef Sep 05 '22 at 09:29

0 Answers0