#๐ 2D list
30 messages ยท Page 1 of 1 (latest)
@north hull
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.
!e
a = [[0]*5]*5
print(a)
a[0][0] = 1
print(a)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
002 | [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
basically they point to the same memory address because of the way you made it
Oh, ok
so
a = [0]*5 # makes a deep copy and
b = [[0]*5]*5 # makes a shallow copy of the inner list?
yeah it's essentially b = [a] * 5
And is there an easy way to change that?
you can't make a deepcopy without copy.deepcopy
every copy is a shallow copy, it just depends on if the data is mutable or not
First isn't a deep copy, it's just int is immutable.
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)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
002 | [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
why is an int immutable?
because that's how it works
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
So I basically just have to add the inner lists with an for loop
yes, that way it creates a new list each time
instead of copying an existing list 5 times
Great, thank you!
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
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.