DEV Community

Rivier Grullon
Rivier Grullon

Posted on

Understanding 2D array (with python)

2D Array

Two dimensional array is an array within an array inside, in this type of array the position of a data element is refered by two indices , it's represents a table with row and columns of data. An example of this can be a recolect of the temperature in a week:

  • Day 1 - 11, 12, 5, 2
  • Day 2 - 15, 6, 10
  • Day 3 - 10, 8, 12, 5
  • Day 4 - 12, 15,8, 6

In ther array this can be represented like this:

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

Accesing values in a two dimensional array

How I write before for you can acces of a specific value of the array, you have to use two indices. One index referring to the parent array and other to refer the position inside the parent:

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

print(T[1][2])
Enter fullscreen mode Exit fullscreen mode

When the code above is execute the output is

10

To printe the entire 2d array we can use the for loop to iterate this:

for r in T:
    for c in r:
        print(c, end = " ")
   print()

Enter fullscreen mode Exit fullscreen mode

output:

11 12 5 2
15 6 10
10 8 12 5
12 15 8 6

Inserting values in the two dimensional array

We can insert new data at specific position by using the insert() method and specifying the index:

T.insert(2, [0,5,11,13,6])

for r in T:
    for c in r:
        print(c,end = " ")
    print()
Enter fullscreen mode Exit fullscreen mode

output:

11 12 5 2
15 6 10
0 5 11 13 6
10 8 12 5
12 15 8 6

Updating values in two dimensional array

We can edit the entire inner array or some specific element by reassigning the values using the array index:

T[2] = [ 11, 9]
T[0][3] = 7

Now the array will be:

11 12 5 7
15 6 10
11 9
12 15 8 6

Deleting the values in two dimensional array

We can also delete the entire inner array or some specific data using the index and the keyword del before:

del T[3]

The array will be:

11 12 5 2
15 6 10
10 8 12 5


`

Thank you for read.

Top comments (0)