Python List Multiplications — It’s a Trap!
An odd case I encountered while working on my project. I need a 3x3 grid represented by 2-dimensional array. To avoid typing the whole array by hand, list multiplications immediately came to mind.
So instead of writing:
arr = [[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]I initialized the array as follows:
arr = [[1] * 3] * 3The list multiplication seemed so neat and simple at the time, until I ran into a problem later when trying to modify the values inside.
Changing value at 2nd row, 2nd column to zero: arr[1][1] = 0 , I was hoping to modity the grid as follows
arr = [[1, 1, 1],
[1, 0, 1],
[1, 1, 1]]However, the array became as follows:
[[1, 0, 1],
[1, 0, 1],
[1, 0, 1]]Explanation
The assignment arr[1][1] = 0 causing each row of the grid to change is because * in creation of the array is copying the address of the first dimension [1, 1, 1] . Instead of copying the items, list multiplication replicates references to the same item: a shallow copy. The list multiplication actually works in the first dimension but not the second:
lst = [1] * 3
lst[0] = 0
lst
>>> [0, 1, 1]Other Possible Implementations
- Nested for-loops
arr = [[1 for i in range(3)] for j in range(3)]- For loop with list multiplication in inner lists
arr = [[1] * 3 for i in range(3)]- List multiplication but with deep copy for inner lists, here
lst[:]is used to obtain a deepcopy of the original array hence the return array won’t be affected by any changes in the original objects.
arr = [x[:] for x in [[1] * 3] * 3]The 3rd method list multiplication turns out to be the fasted among all three, method 2 quite similar and method 1 being the slowest:


Comparing the operations for creating a much larger grid, method 2 and 3 are clearly much more efficient than the first as well.

Final Note
Beware of the difference and usages for shallow & deep copy as a wrong copy in data might lead to series error in production. For more on shallow and deep copy, refer to my previous article under Section Copy: Shallow vs Deep.
Thanks for reading and stay tuned for more articles on Python!






