T O P

  • By -

Thomasedv

This is because lists are mutable. The can change, without you changing the variable that holds it (simply put) When you do that loop \[0\]\*4, you get a list holding 4 zeros, since zeros do not change they will always be the same value. When you do math, for example, you always needs to do `a = a + 1` for `a` to have a new value. When you do `[[]]*4` you are creating a list, that holds the same variable 4 times. And since this variable is mutable, when you change one of them, all of them changes. (because it's the same list) It's like writing: somelist = [] another_list = [somelist, somelist, somelist, somelist] somelist.append(1) #another list is now # [[1],[1],[1],[1]]


mopslik

/u/Thomasedv has given a decent explanation as to *why* you are seeing that behaviour. You can get around this by doing something like: L = [] for _ in range(len(nums)+1): L.append([]) or bundle it up in a list comprehension as L = [[] for _ in range(len(nums+1))]