0

I found the answer to this question very helpful, but I have never seen the keyword None used in such a way before and cannot understand what it's function is in the below block of code:

def get_matrix(self, n, m):
    num = 1
    ***matrix = [[None for j in range(m)] for i in range(n)]***
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            matrix[i][j] = num
            num += 1
    return matrix

If anyone is able to clarify, thank you in advance and I will rename the question to more accurately reflect the topic involved.

  • 1
    @ggorlen: It's both a keyword and an object (like `True` and `False` in Py3); you can tell the difference because it's a valid name, but you can't name anything else `None` (it's like `True` and `False` in that way). The `keyword` module includes it in `kwlist`. – ShadowRanger Dec 22 '20 at 00:14
  • 1
    The whole function body could be `return [[j + i*m + 1 for j in range(m)] for i in range(n)]` instead. `None` was just a placeholder to then fill out the array. – Mark Tolonen Dec 22 '20 at 00:16

1 Answers1

1

It's creating a 2D array of None before populating it. The value of the array doesn't really matter, since it is reassigned later, but None takes less space than other types (specifically, numbers, since that is what is being stored here)

Related - How to define a two-dimensional array?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245