06.0 Python‎ > ‎Python Notes‎ > ‎

Python: 2D arrays

Python does not have true multi-dimension arrays, but structures can be built to hold 2D 
Here are a few different ways of creating 2D arrays:

Two ways to create a 2D array

    # empty matrix 
    matrix = [] 
    print(matrix) 
    # creates a 10 row by 5 column array 
    for row in range(10): 
        # append a new row to the matrix 
        matrix.append([]) 
        for col in range(5): 
            #append a new element to the current row 
            matrix[row].append(row * 10 + col) 
            # matrix = [[0 for i in xrange(5)] for i in xrange(5)] 


This will do the same as the above
    matrix = [[+col + row * 10 for col in range(5)] for row in range(10)] 

Printing 2D arrays

    # print the matrix one row at a time 
    # will print an extra empty list [] 
    print ("print one row at a time") 
    for r in matrix: 
        print(r) 
 
    # print a row at a time 
    print ("another way to print one row at a time") 
    for r in range(10): 
        print(matrix[r]) 
 
    # print an element at a time 
    print ("one element at a time") 
    for r in range(10): 
        for c in range(5): 
            print(matrix[r][c]) 
 
    # print the element from row 6, col 2 
    print ("the element from row 6 col 2") 
    print(matrix[6][2]) 
 
 
    print ("the matrix") 
    print(matrix) 

    print ("ways to print row 2") 
    print(matrix[2][:3]) 
    print(matrix[2]) 

    print ("print rows 1 and 2") 
    print(matrix[1:3]) 
    print() 
 
    print (column(matrix,0)) 
    matrix = [[+col + row * 10 for col in range(3)] for row in range(5)] 
    print(matrix) 
    m = [] 
    m.append(matrix[2] for c in range(1)) 
    #print(m) 

Extract column from a matrix

def column(matrix, i): 
    return [row[i] for row in matrix] 
 


Comments