Home > Blockchain >  What is the difference between multiplying an array and looping to create one?
What is the difference between multiplying an array and looping to create one?

Time:07-13

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)

CodePudding user response:

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], [], []]

CodePudding user response:

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
  • Related