Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way to create a 2D matrix in Python [duplicate]

Possible Duplicate:
How to initialize a two-dimensional array in Python?

I have always written this part of code in this way: every time I need it, I use this python code:

for x in range(8):
        a.append([])
        for y in range(8):
            a[x].append(0)

However, I'd like to know if there's a way to beautify this piece of code. I mean, how do you create a bidimensional matrix in python, and fill it with 0?

like image 341
user1068051 Avatar asked Dec 10 '11 17:12

user1068051


2 Answers

Use nested list comprehensions:

a = [[0 for y in range(8)] for x in range(8)]

which is eqivalent to

a = []
for x in range(8):
    row = []
    for y in range(8):
        row.append(0)
    a.append(row)
like image 164
unutbu Avatar answered Oct 15 '22 15:10

unutbu


Try this:

a = [[0]*8 for _ in xrange(8)]

It uses list comprehensions and the fact that the * operator can be applied to lists for filling them with n copies of a given element.

Or even better, write a generic function for returning matrices of a given size:

# m: number of rows, n: number of columns
def create_matrix(m, n):
    return [[0]*n for _ in xrange(m)]

a = create_matrix(8, 8)
like image 37
Óscar López Avatar answered Oct 15 '22 16:10

Óscar López