Diferrence in inititializing array in python by these methods

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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])) 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x