'Diferrence in inititializing array in python by these methods [duplicate]
I declared an array of array by two methods:
Method 1:
bucket = [[]] * 6)
Method 2:
bucket = [[] for i in range(6)]
but while appending elements to the inner array it works diferrently.
bucket[0].append(1)
print(bucket)
the results come out to be this:
When using Method 1:
Output:
[[1], [1], [1], [1], [1], [1], [1]]
When using Method 2:
Output:
[[1], [], [], [], [], [], []]
I want to understand why this is giving me two different type of results.
Solution 1:[1]
So this is what happening:
- when you do this
bucket = [[]]*(len(nums)+1)all the nested lists
are same. - To confirm that you can
print(id(bucket[0]))andprint(id(bucket[1])). - Both will print same memory address as all are same. So, when you append value to any of the nested list it's get printed for all of the nested list as it's same list object.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
