Skip to content

Instantly share code, notes, and snippets.

@philipkiely
Last active June 16, 2020 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipkiely/7c5d075ae8a1807cc7dc965c7fca2e04 to your computer and use it in GitHub Desktop.
Save philipkiely/7c5d075ae8a1807cc7dc965c7fca2e04 to your computer and use it in GitHub Desktop.
A quick explanation of a python bug to watch out for
# 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)]
@ilknarf
Copy link

ilknarf commented Jun 16, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment