0

I was developing some code involving Python lists. I have initialized them in two manners:

1. a1 = [[0] * 5] * 5
2. a2 = [[0 for _ in range(5)] for _ in range(5)]

When I try to assign values to the elements this is the result:

a1[0][0] = 1
a2[0][0] = 1

a1 => [[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]]

a2 => [[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]]

Python is keeping the same (x and y) references for all objects in the list for a1, but for a2, individual references are used. Is this an expected behavior?

Yore
  • 384
  • 1
  • 4
  • 18

1 Answers1

0

Yes, this is expected behavior. When you do list * 5, Python makes a shallow five-fold copy. The added lists are not new lists that happen to have the same contents; they point to the exact same list in memory.

a = [list1, list2]
b = a*2
# Here, b equals [list1, list2, list1, list2].
# If you append something to b[0],
# you are implicitly appending it to b[2] as well,
# since they are the exact same list.
Artie Vandelay
  • 436
  • 2
  • 10
  • no, it *doesn't make a copy at all* – juanpa.arrivillaga Aug 05 '22 at 16:05
  • @juanpa.arrivillaga Perhaps I should have been more specific: what I mean with "copy", is that only the references to all the elements are copied. The lists inside the toplevel list are not shallow-copied, their references are just taken and duplicated to make the list 5x as long. – Artie Vandelay Aug 05 '22 at 17:20