Last active
June 16, 2020 19:03
-
-
Save philipkiely/7c5d075ae8a1807cc7dc965c7fca2e04 to your computer and use it in GitHub Desktop.
A quick explanation of a python bug to watch out for
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# When working with nested lists created with []*x, watch out for this bug: | |
a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] | |
a[0][1] += 1 | |
print(a) | |
# gives [[0, 1, 0], [0, 0, 0], [0, 0, 0]] | |
# totally straightforward! but … | |
a = [[0]*3]*3 | |
a[0][1] += 1 | |
print(a) | |
# gives [[0, 1, 0], [0, 1, 0], [0, 1, 0]] | |
#even though | |
[[0, 0, 0], [0, 0, 0], [0, 0, 0]] == [[0]*3]*3 | |
# is True | |
# Probably due to the []*x syntax making a deep copy as opposed to a shallow one. | |
# If you want a list that behaves like the first a, use: | |
[[0 for x in range(3)] for x in range(3)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice explanation.
[]*x
copies the references of what is inside the list. It's fine for immutable values, but as demonstrated, the nested list's reference gets copied to create the final list. Similar "results" can be found when using an object constructor instead of a list.