Search code examples
python-3.xfunctionfor-looplocal-variables

i've a local variable unused in a function that made a matrix


I've a local variable that's not used in a function. This function does a matrix and returns that matrix empty.

I've tried to use 'i' variable using an "if i is None: pass" but the issue continue.

def create_matrix(rows, columns):
    matrix = [[None] * columns for i in range(rows)]
    return matrix

i want to dismiss this issue. Is there any way to do it? I know it's a stupid problem but i'm a little bit obsessed with have my code fully clean.


Solution

  • There's no issue if you never use an iterator variable. i in your code behaves like an iterator in a for that is not used:

    for (int i = 0; i < 10; i++)
      // do something without using i
    

    This would be ok in any language like C, C++, PHP...

    However, if you really don't want named variables that are not used in any expression, you call it _:

    def create_matrix(rows, columns):
        matrix = [[None] * columns for _ in range(rows)]
        return matrix
    

    The _ variable is a implicit variable. It always exists, so you are not declaring anything new. It always has the value of the last evaluated expression and may be used in fors like that.