Search code examples
python-3.xgrid-layout

how does this code generate a grid?


I am following a series on tutorials on Object oriented programming. The class matrix is defined as following:

class Matrix():

def __init__(self, rows, columns, default_character='@'):
    self.rows = rows
    self.columns = columns
    self.default_character = default_character

    self.grid = [[default_character] * columns for _ in range(rows)]

def print_matrix(self):
    for row in self.grid:
        print(''.join(row))

The problem is that I do not understand completely how the following line works:

self.grid = [[default_character] * columns for _ in range(rows)]


Solution

  • That is a list comprehension, which is merely a concise way to create lists. The same list could be created with:

        self.grid = []
        for _ in range(rows):
            self.grid.append([default_character] * columns)