0
nums = [1,1,1,2,2,0,3]

lst1 = [[]] * (len(nums) + 1)
lst2 = [[] for i in range(len(nums) + 1)]

print(lst1)        #[[], [], [], [], [], [], [], []]
print(lst2)        #[[], [], [], [], [], [], [], []]

lst1[3].append(2)  
lst2[3].append(2) 

print(lst1)        #[[2], [2], [2], [2], [2], [2], [2], [2]]
print(lst2)        #[[], [], [], [2], [], [], [], []]

Why does lst1 append the element everywhere? Is it because only one empty list is created and is shared by reference? Why would that even be useful?

  • yes, your assumption is correct. Check out : https://stackoverflow.com/questions/2397141/how-to-initialize-a-two-dimensional-array-in-python and/or https://stackoverflow.com/questions/6667201/how-to-define-a-two-dimensional-array – JonSG Jan 11 '23 at 20:45
  • " Is it because only one empty list is created and is shared by reference?" yes, although, "shared by reference" isn't really standard terminology, but you pretty much get it. In that case, you create a list with *multiple references to the same list*. Or to put it even more simply, "the list contains the other list multiple times:". Python containers and objects (typically) have references to other objects. "by reference" is a redundant way to say it. – juanpa.arrivillaga Jan 11 '23 at 20:48

0 Answers0