Python variables
last modified November 29, 2026 Python 3.15
In this article we show how to work with variables in Python.
A variable is a name that refers to a value. In Python, a variable is created the first time a value is assigned to it; there is no separate declaration. The value itself is an object stored in memory, and the variable is only a label attached to it. One object can have several names, and a name can later be attached to a different object, even to an object of another type.
This article covers creating and naming variables and the different forms of assignment. Where a variable is visible is the subject of Python variable scope, and the kinds of values that variables hold are described in Python data types.
Creating variables
A variable is created with the assignment statement. The name is on the
left side of the = sign and the value on the right side.
city = "Bratislava" population = 475_503 area = 367.6 print(city) print(population / area)
Three variables are created: a string, an integer, and a floating point
number. The underscores in 475_503 only make the literal
easier to read. Once a variable exists, its name can be used in
expressions wherever the value is needed; the last line computes the
population density.
$ python first_variables.py Bratislava 1293.5337323177366
Rebinding and dynamic typing
Python is dynamically typed. Types belong to values, not to variables, so the same name can refer to values of different types during the run of a program. Assigning to an existing name rebinds it to the new value.
value = 42 print(value, type(value)) value = "forty-two" print(value, type(value)) value = [4, 2] print(value, type(value)) count = 10 count = count + 5 print(count)
The value name refers first to an integer, then to a string,
and finally to a list. The type function reports the type of
the object that the name refers to at that moment. In
count = count + 5 the right side is evaluated first, using the
old value, and the result is then bound to the name.
$ python rebinding.py 42 <class 'int'> forty-two <class 'str'> [4, 2] <class 'list'> 15
Variable names
A variable name, or identifier, starts with a letter or an underscore and
continues with letters, digits, and underscores. Letters are not limited to
ASCII; most Unicode letters are allowed. Names are case sensitive.
Keywords such as class or for cannot be used as
names.
import keyword
width = 80
Width = 120
WIDTH = 200
print(width, Width, WIDTH)
_hidden = "internal"
user_name2 = "Peter"
größe = 1.85
print(_hidden, user_name2, größe)
print(keyword.iskeyword("class"))
print(keyword.iskeyword("klass"))
print(keyword.softkwlist)
width, Width, and WIDTH are three
different variables. A leading underscore is allowed and by convention
marks a name for internal use. The keyword module tells which
words are reserved. Soft keywords, such as match,
case, and type, are reserved only in specific
places and can still serve as variable names elsewhere. Python 3.15 added
lazy, used in lazy imports, to the list.
$ python names.py 80 120 200 internal Peter 1.85 True False ['_', 'case', 'lazy', 'match', 'type']
Invalid names
A name cannot start with a digit. Such a mistake is detected when the source file is compiled, before any statement of the file runs.
print("checking names")
2nd_place = "silver"
The parser reads 2nd_place as a number followed by letters
and reports a SyntaxError. Note that even the first print
statement does not run, because the whole file is rejected.
$ python bad_name.py
File "/home/user/variables/bad_name.py", line 2
2nd_place = "silver"
^
SyntaxError: invalid decimal literal
Multiple assignment and unpacking
Several variables can be assigned in one statement. When the left side lists several names separated by commas, the value on the right is unpacked: its items are assigned to the names in order.
x, y = 3, 4 print(x, y) x, y = y, x print(x, y) name, age, city = ["Lucia", 28, "Košice"] print(name, age, city) first, *rest = [7, 1, 9, 4] print(first, rest) *init, last = "tuple" print(init, last) a = b = c = 0 print(a, b, c)
x, y = y, x swaps two values without a temporary variable;
the right side is evaluated completely before any name is rebound. The
number of names must match the number of items, unless one name is marked
with a star. The starred name collects the remaining items into a list.
The chained form a = b = c = 0 binds all three names to the
same object.
$ python unpacking.py 3 4 4 3 Lucia 28 Košice 7 [1, 9, 4] ['t', 'u', 'p', 'l'] e 0 0 0
Augmented assignment
Augmented assignment combines an operation with an assignment.
total += price is a shorter form of
total = total + price. Every binary arithmetic and bitwise
operator has an augmented form.
total = 0
for price in [12.5, 3.0, 7.25]:
total += price
print(total)
stock = 50
stock -= 8
print(stock)
level = 3
level *= 4
level //= 5
level **= 2
print(level)
label = "item"
label += "-01"
print(label)
flags = 0b0001
flags |= 0b0100
print(bin(flags))
The loop adds up prices in total. The level
variable is multiplied, floor-divided, and raised to a power in place:
3 * 4 is 12, 12 // 5 is 2, and 2 ** 2 is 4. For strings,
+= concatenates, and |= sets a bit in an
integer used as a set of flags. The variable must exist before an
augmented assignment is applied to it.
$ python augmented.py 22.75 42 4 item-01 0b101
Names refer to objects
Assigning one variable to another does not copy the value. Both names then refer to the same object. Whether this matters depends on whether the object can be changed in place.
a = 500
b = a
print(a is b, id(a) == id(b))
a += 1
print(a, b, a is b)
colours = ["red", "green"]
palette = colours
palette.append("blue")
print(colours)
print(palette is colours)
palette = palette + ["black"]
print(colours)
print(palette)
print(palette is colours)
After b = a, both names refer to the same integer object, as
the is operator and the id function confirm.
Integers are immutable, so a += 1 creates a new object and
rebinds a; b still refers to 500. A list is
mutable: palette.append changes the one list that both
palette and colours refer to. The expression
palette + ["black"], on the other hand, builds a new list, and
the assignment moves only the palette name to it. Copying
objects is covered in
Python copy by value vs
reference.
$ python aliasing.py True True 501 500 False ['red', 'green', 'blue'] True ['red', 'green', 'blue'] ['red', 'green', 'blue', 'black'] False
Deleting variables
The del statement removes a name. It deletes the variable,
not necessarily the object; the object is freed only when no other name or
container refers to it.
temp = 21.5
print(temp)
del temp
print("temp deleted")
print(temp)
After del temp, the name no longer exists. Using it raises a
NameError, the same error as for a name that was never
assigned. Exceptions are explained in
Python exceptions.
$ python deleting.py
21.5
temp deleted
Traceback (most recent call last):
File "/home/user/variables/deleting.py", line 6, in <module>
print(temp)
^^^^
NameError: name 'temp' is not defined
Constants
Python has no constant declarations. By convention, names written in
capital letters denote values that should not change. The
Final annotation from the typing module states
the same intent in a form that static type checkers can verify.
from typing import Final MAX_USERS: Final = 100 TAX_RATE = 0.2 price = 80 print(price * (1 + TAX_RATE)) MAX_USERS = 150 TAX_RATE = 0.25 print(MAX_USERS, TAX_RATE)
Neither form is enforced when the program runs: both reassignments
succeed. A type checker such as mypy reports the reassignment of
MAX_USERS because it is marked Final; the
capitalised TAX_RATE is protected only by the convention.
$ python constants.py 96.0 150 0.25
Type annotations
A variable can carry a type annotation, written after a colon. The annotation documents the intended type and is used by type checkers and editors. The interpreter does not check it.
count: int = 0
ratio: float = 0.5
names: list[str] = ["Jan", "Eva"]
count = "many"
print(count)
limit: int
print("limit annotated")
print(limit)
Assigning a string to count, annotated as an integer, works
at runtime. An annotation without a value, such as
limit: int, does not create the variable at all; reading
limit afterwards raises a NameError. The message
suggests the similar name list.
$ python annotations.py
many
limit annotated
Traceback (most recent call last):
File "/home/user/variables/annotations.py", line 10, in <module>
print(limit)
^^^^^
NameError: name 'limit' is not defined. Did you mean: 'list'?
The underscore name
A single underscore is a valid variable name. By convention it marks a value that is required by the syntax but not used afterwards.
for _ in range(3):
print("tick")
name, _, salary = ["Robert", "ignored", 2300]
print(name, salary)
first, *_, last = [3, 8, 2, 9, 5]
print(first, last)
million = 1_000_000
print(million)
The loop runs three times, and the loop variable is not needed. In the
unpacking statements, _ takes the middle item and
*_ takes all items between the first and the last. Inside a
numeric literal such as 1_000_000, underscores are digit
separators, which is a different use of the character.
$ python underscore.py tick tick tick Robert 2300 3 5 1000000
Where variables are stored
Variables assigned at the top level of a file are global variables of the
module. They are stored in a dictionary, which the globals
function returns. The module also has special variables set by Python, such
as __name__.
print(__name__)
city = "Žilina"
print("city" in globals())
print("town" in globals())
print(globals()["city"])
__name__ is __main__ because the file is run as
a program; in an imported module it holds the module name. The dictionary
returned by globals maps variable names to their values. Names
assigned inside a function are local to that function; see
Python variable scope and
Python global keyword.
$ python special_names.py __main__ True False Žilina
Source
Assignment statements, Identifiers and keywords, Naming and binding, typing.Final
In this article we have created variables with assignment, looked at the rules for names, rebound names to values of other types, used multiple, starred, and augmented assignment, seen that names refer to shared objects, deleted names with del, and marked constants and types with conventions and annotations. See also Python variable scope, Python variable shadowing, Python walrus operator, and Python data types.
Author
List all Python tutorials.