2D array python code example

Example 1: how to input 2-d array in python

matrix = [input().split() for i in range(no_of_rows)] # if only row is given and the number of coloumn has to be decide by user
matrix= [[input() for j in range(no_of_cols)] for i in range(no_of_rows)] # if both row and coloumn has been taken as input from user

Example 2: 2d array python

array = [[value] * lenght] * height

//example
array = [[0] * 5] * 10

print(array)

Example 3: create a 2d array in python

def build_matrix(rows, cols):
    matrix = []

    for r in range(0, rows):
        matrix.append([0 for c in range(0, cols)])

    return matrix

if __name__ == '__main__':
    build_matrix(6, 10)

Example 4: 2d array in python

from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
for r in T:
    for c in r:
        print(c,end = " ")
    print()

Example 5: python print 2d array as table

for row in A:
    for val in row:
        print '{:4}'.format(val),
    print

Example 6: 2D array python

# 2D arrays in python can be used to create rudimentary games

array_2d = [['row0, column0'], ['row0, column1'], ['row0, column2'],
            ['row1, column0'], ['row1, column1'], ['row1, column2'],
            ['row2, column0'], ['row2, column1'], ['row2, column2']]

Tags:

Misc Example