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. 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.

Sign up to request clarification or add additional context in comments.

12 Comments

Or an UnboundLocalError
@dr_andonuts, what do you mean "variable not being defined"? An example is appreciated. Thanks. :)
@LinMa When a variable is assigned a value, it becomes defined. Until that point, it is undefined.
@dr_andonuts, in what scenario Python will automatically assign/initialize None to a variable? No such scenario? Thanks.
@LinMa Python will never automatically assign None to a variable. It will never automatically assign any value to a variable.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.