0

When running class code:

class foo():
    r = 2
    c = 2
    a = [[0 for i in range(c)] for j in range(r)]
    print(a)

foo()

This error is generated:

NameError: name 'c' is not defined

Though both r and c are show if using the locals() call after the definitions.

Admittingly a little bit weird, but still code encountered in real life :-)

Why is the c variable not visible in the inner list comprehension?


For comparison, when running this function code:

def foo():
    r = 2
    c = 2
    print(locals())
    a = [[0 for i in range(c)] for j in range(r)]
    print(a)

foo()

The expected result is shown:

[[0, 0], [0, 0]]

Both r and c are also show if using the locals() call after the definitions.

EquipDev
  • 5,573
  • 10
  • 37
  • 63

0 Answers0