In Python, a 2D array (or matrix) is essentially a list of lists. You can access elements, rows, and columns in a 2D array using indexing.
Here's how you can do it:
Accessing an element: To access an element in a 2D array, you use two indices. The first index is for the row and the second index is for the column. For example, matrix[i][j]
will give you the element at the ith row and jth column.
Accessing a row: To access a row in a 2D array, you only need one index. For example, matrix[i]
will give you the ith row.
Accessing a column: Accessing a column is a bit trickier because Python's list of lists structure does not have built-in support for accessing columns. You typically use a loop or a list comprehension to access a column. For example, [row[j] for row in matrix]
will give you the jth column.
Suppose you want to access all of the items present in one row of a 2-dimensional array or a matrix and change it to some value(let's say 0 to 1), then you can do it this way:
// creating a matrix initializing 0 at all of the indices
matrix = [[0]*n for i in range(m)] # n = number of cells in a row or number of columns and m = number of rows
for i in range(n):
matrix[row_number][i] = 1
If you want to access a particular column in the matrix, and change all the values of the column in a matrix to 1, then you can do this:
for j in range(m):
matrix[j][column_number] = 1
Insert Method in python
arr.insert(i, n) #Here 'i' is the index and 'n' is any number
Note: When we Insert any number 'n' in the array using insert method, then it slides the remaining right side elements of the array to right
for example
arr = [1,2,3,4,5]
arr.insert(3, 1)
print(arr) //OUTPUT: [1,2,3,1,4,5]
If you have any feedback, then you can DM me on Twitter or Linkedin.
Top comments (0)