0

For some reason when I do the second one it works the way I want to, but when I used the first one and I try to append it appends to all lists. Specifically the line at the bottom is where the difference happens.

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

        for key, val in myMap.items():
            count[val].append(key)
  • https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – Nin17 Jul 12 '22 at 21:07

2 Answers2

0

With the first option, all the sublists, are pointing to the same list, because you are "cloning" the reference. So if you modify one, all will be modified:

count = [[]] * (3)
print(count)  # [[], [], []]
count[0].append(1)
print(count)  # [[1], [1], [1]]

Otherwise, making list comprenhension (looping), will create diferent sublists, because you are instantiating a new list in each iteration. So if you modify one, only that will be modified:

count = [[] for i in range(3)]
print(count)  # [[], [], []]
count[0].append(1)
print(count)  # [[1], [], []]
Rodrigo Llanes
  • 613
  • 2
  • 10
  • How is this different than [0] * 26 because when I modify those it doesnt change them all – – JEBIN JOHN Jul 12 '22 at 21:28
  • @JEBINJOHN, the diference is that 0 is an integer, and the integers are primiteves, they are not objects, so python will not copy the pointer, it will copy the value. The 4 python primitives are integers, floats, strings and booleans. – Rodrigo Llanes Jul 12 '22 at 21:44
0

First version is simply multiplying same object. There are no n different lists here. All are the same list.

count = [[]] * (len(nums) +1)

print(count)
[[], [], [], []]

We can easily see this by printing these lists` id. They are exactly same. So if you append new element let's say on the first list, it'll appear in others too. Because they are same.

print(f"first - {id(count[0])}")
print(f"second = {id(count[1])}")

count[0].append(1)
print(count)
first - 4310957440
second -4310957440
[[1], [1], [1], [1]]

On the second version, you generate new lists and they are different. You can check yourself by printing the ID values.

count = [[] for i in range(3+1)]

print(count)
[[], [], [], []]
print(f"first - {id(count[0])}")
print(f"second = {id(count[1])}")
first - 4310956160
second -4310940416
Arzu Huseynov
  • 190
  • 1
  • 8