Definition of a variable in Python
A variable in Python is a symbolic name that refers to a value stored in memory. Unlike other programming languages, Python does not require you to explicitly declare a variable's type: it is automatically inferred at the time of assignment. This is called dynamic typing.
In other words, a variable is like a label you stick on a box to identify what it contains. You can change the contents of the box at any time, and the label will automatically adapt. If you want to deepen your understanding of this fundamental concept along with all the other pillars of the language, we recommend following our complete Python course which covers this topic in detail.
Here is a simple example of creating a variable:
name = "Alice"
age = 30
height = 1.72
is_active = TrueIn this example, we created four variables of different types: a string, an integer, a floating-point number, and a boolean. Python automatically inferred the type of each one.
How to declare and assign a variable
In Python, declaring and assigning a variable happen simultaneously using the = operator. There is no specific keyword like var or let as found in other languages.
Simple assignment
The most common form is to assign a single value to a single variable:
# Simple assignment
first_name = "Marie"
points = 100
pi = 3.14159
Multiple assignment
Python allows you to assign multiple variables in a single line, which can make your code more concise:
# Multiple assignment on a single line
x, y, z = 10, 20, 30
# Assigning the same value to multiple variables
a = b = c = 0
print(x, y, z) # 10 20 30
print(a, b, c) # 0 0 0
Reassignment and type change
Thanks to dynamic typing, you can reassign a variable with a value of a completely different type:
my_variable = 42
print(type(my_variable)) #
my_variable = "Hello"
print(type(my_variable)) #
my_variable = [1, 2, 3]
print(type(my_variable)) # Although changing types is possible, it is generally discouraged in professional code. It can make the code difficult to understand and debug. Try to keep a consistent type for each variable.
Fundamental data types
Each variable in Python has a type that determines which operations you can perform on it. Here are the most common data types:
| Type | Description | Example |
|---|---|---|
int | Integer | age = 25 |
float | Floating-point number | price = 19.99 |
str | String | name = "Python" |
bool | Boolean (True/False) | active = True |
list | Ordered and mutable list | fruits = ["apple", "pear"] |
tuple | Ordered and immutable tuple | coords = (10, 20) |
dict | Key-value dictionary | info = {"name": "Alice"} |
set | Unordered unique set | uniques = {1, 2, 3} |
NoneType | Absence of value | result = None |
You can check the type of a variable at any time with the type() function, and you can leverage structures like list, tuple, dict, or set to organize your data.
value = 3.14
print(type(value)) #
print(isinstance(value, float)) # True
print(isinstance(value, int)) # False
Naming conventions
Python has strict rules and strongly recommended conventions for naming your variables. Following them is essential for writing readable and professional code.
Mandatory rules
- A variable name must start with a letter (a-z, A-Z) or an underscore (
_). - It can contain letters, digits, and underscores.
- It cannot start with a digit.
- It cannot contain spaces or special characters (except
_). - It is case-sensitive:
name,Name, andNAMEare three different variables. - It cannot be a Python reserved keyword (such as
if,for,while, class, def, lambda, global, nonlocal, yield, etc.).
Recommended conventions (PEP 8)
PEP 8, the official Python style guide, recommends the following conventions:
# ✅ Good naming practices
user_name = "Alice" # snake_case for variables
MAX_COUNT = 100 # UPPERCASE for constants
_private_variable = "internal" # underscore to indicate private use
# ❌ Bad practices
userName = "Alice" # camelCase (not recommended in Python)
x = "Alice" # too short and not descriptive
data = [1, 2, 3] # too vagueAlways choose descriptive variable names. A good variable name is one that allows you to immediately understand its purpose without needing to read the rest of the code.
Variable scope
The scope of a variable determines where it is accessible in your program. Python follows the LEGB rule: Local, Enclosing, Global, Built-in.
Local variables
A variable defined inside a function (def) is only accessible within that function:
def greet():
message = "Hello!" # Local variable
print(message)
greet() # Hello!
# print(message) # ❌ NameError: name 'message' is not defined
Global variables
A variable defined outside any function is a global variable, accessible from anywhere in the module:
counter = 0 # Global variable
def increment():
global counter # Declare the intention to modify the global variable
counter += 1
increment()
print(counter) # 1Excessive use of global variables is strongly discouraged. They make the code harder to test, debug, and maintain. Prefer passing values as function parameters.
Enclosing variables
In nested functions, you can access variables from the enclosing function using the nonlocal keyword:
def outer():
value = 10
def inner():
nonlocal value
value += 5
print(f"Inner value: {value}")
inner()
print(f"Outer value: {value}")
outer()
# Inner value: 15
# Outer value: 15
Variables and objects in memory
In Python, variables do not directly contain values: they are references to objects in memory. Understanding this mechanism is fundamental to avoiding unexpected behaviors.
Identity and reference
You can check the identity of an object with the id() function:
a = [1, 2, 3]
b = a # b points to the same object as a
print(id(a) == id(b)) # True: same object in memory
b.append(4)
print(a) # [1, 2, 3, 4] — a is also modified!
Copy vs reference
To create an independent copy of a mutable object, you must explicitly use a copy method:
import copy
# Shallow copy
original_list = [1, 2, [3, 4]]
copied_list = original_list.copy() # or list(original_list)
copied_list[0] = 99
print(original_list) # [1, 2, [3, 4]] — not modified
# Be careful with nested objects
copied_list[2].append(5)
print(original_list) # [1, 2, [3, 4, 5]] — modified!
# Deep copy to avoid this
deep_list = copy.deepcopy(original_list)
deep_list[2].append(6)
print(original_list) # [1, 2, [3, 4, 5]] — not modified
Mutable vs immutable objects
This distinction is crucial for understanding variable behavior:
When you modify an immutable object, Python actually creates a new object in memory:
x = 10
print(id(x)) # Ex: 140234866477328
x += 1
print(id(x)) # Ex: 140234866477360 — new object!
Type annotations (type hints)
Since Python 3.5, you can add type annotations to your variables. They do not change the program's behavior but significantly improve readability and enable the use of static checking tools like mypy.
# Type annotations for variables
name: str = "Alice"
age: int = 30
height: float = 1.72
is_active: bool = True
# Annotations with composite types
from typing import List, Dict, Optional, Tuple
grades: List[int] = [15, 18, 12]
user: Dict[str, str] = {"name": "Alice", "city": "Paris"}
result: Optional[int] = None
coordinates: Tuple[float, float] = (48.8566, 2.3522)Type annotations are purely informational in Python. They do not cause an error if the actual type does not match the annotation. Use tools like mypy to verify type consistency.
Special variables in Python
Python uses certain special variables that you will encounter frequently:
The __name__ variable
The __name__ variable is a special variable automatically defined by Python. It contains the name of the currently executing module:
# script.py
print(__name__) # "__main__" if executed directly
if __name__ == "__main__":
print("This script is being executed directly")
The _ variable
The single underscore _ is conventionally used for values you want to ignore:
# Ignore a value during unpacking
name, _, age = ("Alice", "Dupont", 30)
# Ignore the index in a loop
for _ in range(5):
print("Repetition")
Double underscore variables
Variables surrounded by double underscores (called dunder) are Python special variables like __init__, __new__, or __all__. They play a fundamental role in the internal workings of the language.
Best practices
Here is a summary of essential best practices for working with variables in Python:
- Use descriptive names: prefer
student_countovernorx. - Follow snake_case: this is the Python convention (PEP 8) for variable and function names.
- Limit scope: avoid global variables as much as possible.
- Always initialize your variables: never leave a variable without an initial value.
- Use type annotations: they document your code and help analysis tools.
- Avoid built-in function names: never name a variable
list,dict,str,type, print, or len as this would shadow the native function. - Add comments and docstrings to explain the purpose of complex variables.
- Use constants: for values that never change, use UPPERCASE names.
# ✅ Exemplary code
MAX_ATTEMPTS = 3
user_name: str = "Alice"
student_grades: list[int] = [15, 18, 12, 20]
def calculate_average(grades: list[int]) -> float:
"""Calculate the average of a list of grades."""
return sum(grades) / len(grades)
average = calculate_average(student_grades)
print(f"Average for {user_name}: {average:.2f}")
Frequently asked questions
What is the difference between a variable and a constant in Python?
In Python, there is no true constant in the strict sense of the term. By convention, values that should not be modified are written in UPPERCASE (for example PI = 3.14159). However, nothing technically prevents you from modifying them. It is a convention that all Python developers follow to indicate that a variable should not be changed.
Can you delete a variable in Python?
Yes, you can delete a variable with the del keyword. Once deleted, any attempt to access that variable will raise a NameError:
x = 42
print(x) # 42
del x
# print(x) # ❌ NameError: name 'x' is not definedHowever, explicitly deleting variables is rarely necessary. Python's garbage collector automatically frees the memory of objects that are no longer referenced.
How do you swap the values of two variables in Python?
Python offers an elegant syntax for swapping the values of two variables without needing a temporary variable:
a = 10
b = 20
# Swap in a single line
a, b = b, a
print(a) # 20
print(b) # 10This syntax works thanks to Python's tuple unpacking mechanism. It is one of the features that make the language so enjoyable to use.
How can I learn to use variables effectively in Python?
Variables are the very first concept you need to master in Python. To gain a solid and progressive understanding of variables along with all the other concepts of the language, we recommend following our dedicated Python course on Believemy. You will learn best practices, typing, memory management, and much more through hands-on exercises.