1

version: python 3

The code is straight forward

dp = [[float('inf')] * 3] * 3

dp[0][0] = 1

what I get

  • [[1, inf, inf], [1, inf, inf], [1, inf, inf]]

what I expect to get

  • [[1, inf, inf], [inf, inf, inf], [inf, inf, inf]]

Any clues ?

Jin
  • 17
  • 4

1 Answers1

3

list * number means not a copy of the list but number references to the same list (same memory location). That's why mutating one of the three lists will mutate also the other ones.

A solution could be (create the lists using a loop):

dp = [[float("inf")] * 3 for i in range(3)]

See also: Copy a list of list by value and not reference

Akida
  • 1,076
  • 5
  • 16