2

For Python variable (e.g. List and integer) if we do not initialize it, are they always None? Is there any scenario Python will do initialization for us even if we do not initialize it explicitly?

For initialization, I mean,

Foo = []
Goo = 0

thanks in advance, Lin

1
  • In JavaScript an undefined variable returns undefined but in Python, it would raise a fatal error.
    – jkd
    Commented Apr 15, 2015 at 1:43

1 Answer 1

5

A variable is defined when it is first assigned to a value. Typically, this follows the convention of variable = value. It doesn't become defined until this point, and is defined from this point on until the end of its scope.

If a variable hasn't been defined, attempting to read its data will raise a NameError. On the other hand, [], 0, and None are different types of data values that a defined variable can equal.

Specifically:

  • [] - An array with no elements
  • 0 - The int value equal to the number 0
  • None - A special data type which is meant to denote that a variable does not have a value. This is very different than a variable not being defined.

Python will not initialize a variable automatically -- how could it? Without knowing what kind of data or values will be operated on, Python can't handle an undefined variable. So it throws an exception, specifically a NameError.

12
  • 3
    Or an UnboundLocalError
    – Shashank
    Commented Apr 15, 2015 at 1:14
  • @dr_andonuts, what do you mean "variable not being defined"? An example is appreciated. Thanks. :)
    – Lin Ma
    Commented Apr 15, 2015 at 4:15
  • @LinMa When a variable is assigned a value, it becomes defined. Until that point, it is undefined. Commented Apr 15, 2015 at 5:14
  • @dr_andonuts, in what scenario Python will automatically assign/initialize None to a variable? No such scenario? Thanks.
    – Lin Ma
    Commented Apr 15, 2015 at 7:00
  • @LinMa Python will never automatically assign None to a variable. It will never automatically assign any value to a variable. Commented Apr 15, 2015 at 15:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.