Python - Using 2D arrays/lists the right way

PythonServer Side ProgrammingProgramming

Python provides many ways to create 2-dimensional lists/arrays. However, one must know the differences between these ways because they can create complications in code that can be very difficult to trace out.

Example

 Live Demo

rows, cols = (5, 5)
arr = [[0]*cols]*rows
#lets change the first element of the 1st row to 1 & print the array
arr[0][0] = 1
for row in arr:
   print(row)
arr = [[0 for i in range(cols)] for j in range(rows)]
#again in this new array lets change the 1st element of the first row
# to 1 and print the array
arr[0][0] = 1
for row in arr:
   print(row)

Output

[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]
[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]
raja
Published on 06-Aug-2020 13:17:20
Advertisements