A 2-D array is an “array or arrays”, with 2 index values:
1 2 3 4 5 6 | ROOMS = 4 COMPUTERS = 5 #create array computers = [ ["" for c in range (COMPUTERS)] for r in range (ROOMS)] ... |
Nested loops are used to go through each of the index values:
1 2 3 4 5 6 7 8 9 | ... #populate array for room in range (ROOMS): for computer in range (COMPUTERS): computerID = f "r{room}c{computer}" computers[room][computer] = computerID print (computers) |
Printing a raw 2-D array shows the “array of arrays” structure:
[['r0c0', 'r0c1', 'r0c2', 'r0c3', 'r0c4'], ['r1c0', 'r1c1', 'r1c2', 'r1c3', 'r1c4'], ['r2c0', 'r2c1', 'r2c2', 'r2c3', 'r2c4'], ['r3c0', 'r3c1', 'r3c2', 'r3c3', 'r3c4']]
The printing of a 2-D array can be improved:
1 2 3 4 | for room in range (ROOMS): for computer in range (COMPUTERS): print (computers[room][computer], ' ' ,end = '') print () |
r0c0 r0c1 r0c2 r0c3 r0c4 r1c0 r1c1 r1c2 r1c3 r1c4 r2c0 r2c1 r2c2 r2c3 r2c4 r3c0 r3c1 r3c2 r3c3 r3c4