Q:

how to create 2d list 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)
5
o=[]
for i in range(0,rows):
    x=[]
    for j in range(0,cols):
        x.append(0)
    o.append(x)
#if you use [[0]*cols]*rows all rows will become the same list
#so editing in one row will edit all rows
1
x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)
0
# Using above first method to create a  
# 2D array 
rows, cols = (5, 5) 
arr = [[0]*cols]*rows 
print(arr) 
4

New to Communities?

Join the community