#๐Ÿ”’ 2D list

30 messages ยท Page 1 of 1 (latest)

north hull
#

If I do something like this:

a = [[0]*5]*5
print(a)
a[0][0] = 1
print(a)

Why does it change every first element in each sublist (?), and not only the first element in the first sublist?

proud phoenixBOT
#

@north hull

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

north hull
#

!e

a = [[0]*5]*5
print(a)
a[0][0] = 1
print(a)
proud phoenixBOT
cursive cloud
#

basically they point to the same memory address because of the way you made it

north hull
#

Oh, ok

#

so

a = [0]*5  # makes a deep copy and
b = [[0]*5]*5  # makes a shallow copy of the inner list?
cursive cloud
#

yeah it's essentially b = [a] * 5

north hull
#

And is there an easy way to change that?

pale flint
#

every copy is a shallow copy, it just depends on if the data is mutable or not

spark cobalt
#

First isn't a deep copy, it's just int is immutable.

pale flint
#

instead of doing list multiplication, you can list comprehension instead

#

!e

a = [[0]*5 for _ in range(5)]
print(a)
a[0][0] = 1
print(a)
proud phoenixBOT
north hull
pale flint
#

there's really no reason for an int to be mutable

#

lists/dicts/sets are mutable

#

we can change the data within without needing an assignment

north hull
pale flint
#

yes, that way it creates a new list each time

#

instead of copying an existing list 5 times

north hull
#

Great, thank you!

spark cobalt
# north hull why is an int immutable?

Why wouldn't it?
Any thing you do with an int is var=something+something or other calculation
When you do var= it makes a new reference
Also no methods that would be like var.add(5) and then var has a different value - all methods return a new thing.

As opposed to list where you keep the list but change the inside state of it. my_list[index]=something mutates the my_list - there's no my_list= to overwrite it

north hull
#

I misunderstood what immutable means. Now it makes sense. Thank you!

#

!close

proud phoenixBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.