You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

 

Two-dimensional array (Java) vs Two-dimensional list (Python)

A good representation of a 2-dimensional array (list) is a grid because technically, it is one. A practical application for 2-dimensional lists would be to use them to store the available seats in a cinema, where one dimension represents the rows and other one - columns (seats). Of course, a cinema would be bigger in real life, but this list is just fine as an example. 0 means the seat is available, 1 stands for one that isn't. Later, we could also add 2 for reserved seats and so on.

In Python, we declare the 2D array (list) like a list of lists.

Strings in Java
 
 
Strings in Python
cinema = []
for j in range(5):
	column = []
    for i in range(5):
		Column.append(0)
	Cinema.append(column)

As first, we create an empty one-dimensional list. Then we generate 5 more lists (columns) using a for loop, fill each list with 5 zeros using a nested loop and add the list to the original list as a new item.

The first number indicates the number of columns, the second is the number of rows, we could treat it the other way around as well, for example, matrices in mathematics have the number of rows come first.

We've just created a table full of zeros.

Filling the data

Let's fill the cinema room with 1s now as you can see in the picture above. Since we'll be lazy as good programmers should be, we'll use for loops to create a row of 1s. To access an item of the 2D list we have to enter two coordinates.

Strings in Java
 
Strings in Python
cinema[2, 2] = 1 # center
for i in range(1, 4): # fourth row
        cinema[i][3] = 1
for i in range(5): # the last row
        cinema[i][4] = 1
 

The output

We'll print the list using a loop as we did before. We'll need 2 loops for the 2d list, the first one will iterate over columns and the second one over rows). As proper programmers, won't specify the number of rows and columns directly into the loop because it may change in the future. We know the len() function so we can easily ask how many columns is in the outer list and how many items is in the inner one. We have to keep in mind the outer list can be empty.

We'll nest the loops in order so that the outer loop iterates over the rows and the inner one over the columns of the current row. After printing a row, we must break a line. Both loops must have a different control variable.

Output in Java
 
Output in Python
cols = len(cinema)
rows = 0
if cols:
	rows = len(cinema[0])
for j in range(rows):
    for i in range(cols):
     	print(cinema[i][j], end = "")
    print()
 


  • No labels