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.
CodePudding user response:
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]))
and
print(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.