Variables in Python

In this post I explain how variables work in Python and how names refer to objects.
TopicsPython

Variables in Python

In Python a variable is a name that refers to a location in memory. We use that name to access and reuse data in our program.

Variables let you store values and use them more than once.

Creating a Variable

For example, you can store a number:

x = 6

And then use it in arithmetic expressions:

x * 7  # 42

Naming Rules

A variable name can contain only letters, digits, and the underscore character:

__answer_to_the_ultimate_question = 42

A name must start with a letter or an underscore, not with a digit:

42_is_the_answer = 42  # Error!

Letter case matters, so these are different variables:

X = 42
x = 29
x == X  # False

Data Types in Variables

You can store any Python object in a variable, for example numbers, strings, and other data types:

my_int = 42
my_str = "Hello"
my_float = 0.99
my_bool = True

References to Objects

Variables in Python are references to objects. If you assign one variable to another, both names refer to the same object:

x = 42
y = x

If you later change the value of x, it starts referring to a new object while y still points to the original one:

x = 29
x  # 29
y  # 42

Multiple Assignment

You can assign values to multiple variables at once with a comma:

a, b = 42, 29
a  # 42
b  # 29

This is useful, for example, when you want to swap two variables without a temporary variable:

a, b = 42, 29
a, b = b, a
a  # 29
b  # 42