Every program needs a way to remember information. When you write a Python script that calculates a total, greets a user by name, or tracks a score in a game, you need to store data somewhere the program can find it again. That somewhere is memory, and the tool Python gives you for labeling data in memory is called a variable.
This tutorial walks through the fundamentals of storing data in Python, starting with variable assignment and working up to how Python manages objects and references in memory. By the end, you will be able to create variables, choose good names for them, identify data types, and understand the relationship between a variable name and the object it points to.
What Is a Variable and Why Does It Matter?
A variable is a name you give to a piece of data so you can use it later. Think of it like a label on a storage container. The label is not the container itself, and it is not the item inside. It is just a way to find what you stored.
In Python, creating a variable is straightforward. You write a name, follow it with the = sign (called the assignment operator), and then provide the value you want to store.
username = "Ada"
score = 100
temperature = 36.6
is_active = True
print(username) # Ada
print(score) # 100
print(temperature) # 36.6
print(is_active) # True
Each line above creates a variable and assigns it a value. Python does not require you to declare the type of a variable before using it. The interpreter figures out the type based on the value you assign. This behavior is called dynamic typing, and it is one of the features that makes Python approachable for beginners.
The = sign in Python is the assignment operator, not a statement of equality. It means "make this name point to this value." The double equals sign == is used for comparison instead.
You can also reassign a variable to a new value at any time. Python will simply redirect that name to point to a different object in memory.
color = "blue"
print(color) # blue
color = "green"
print(color) # green
# The variable can even change type
color = 42
print(color) # 42
This flexibility is powerful, but it also means you need to keep track of what a variable currently holds. Using descriptive names helps with that.
Build a valid Python statement that stores the string "Python" in a variable called language:
How Python Stores Data Behind the Scenes
When you write score = 100, two things happen internally. First, Python creates an integer object with the value 100 and places it on a region of memory called the heap. Second, the name score is created as a reference that points to that object's memory address.
This is a crucial distinction: a Python variable is not a box that holds a value. It is a name tag attached to an object that lives somewhere in memory. Understanding this model helps explain several behaviors that confuse beginners.
Use the built-in id() function to see the memory address of any object. In CPython (the standard Python implementation), id() returns a unique integer representing where the object lives in memory.
a = 42
b = a
print(id(a)) # e.g., 140714055169672
print(id(b)) # same number — both point to the same object
print(a is b) # True — they reference the identical object
When you write b = a, Python does not copy the value 42 into a new location. Instead, both a and b become labels attached to the same integer object. This is memory-efficient, and Python takes it further with a technique called interning: for small integers in the range -5 to 256, Python reuses the same objects instead of creating new ones.
What Happens When You Reassign?
If you later write a = 99, Python creates a new integer object for 99 and points the name a at it. The name b still references the original object 42. If no names reference an object anymore, Python's garbage collector eventually reclaims that memory.
a = 42
b = a
print(a is b) # True
a = 99
print(a) # 99
print(b) # 42 — b still points to the original object
print(a is b) # False — they now reference different objects
- Example
count = 10- Mutable?
- No (immutable) -- reassigning creates a new object
- Example
name = "Ada"- Mutable?
- No (immutable) -- you cannot change individual characters in place
- Example
items = [1, 2, 3]- Mutable?
- Yes (mutable) -- you can add, remove, or change items without creating a new list
- Example
is_valid = True- Mutable?
- No (immutable) -- there are only two boolean objects: True and False
- Example
user = {"name": "Ada", "age": 30}- Mutable?
- Yes (mutable) -- you can add, update, or remove key-value pairs
This code stores two temperatures and tries to check whether they reference the same object. One line uses the wrong operator. Click the buggy line, then hit check.
is to == on line 4. The is operator checks whether two names point to the same object in memory (identity), not whether they hold the same value (equality). Two separate float assignments like 18.5 are not interned the way small integers are, so is will return False even though the values match. Use == to compare values.
Data Types, Naming Rules, and Common Patterns
Python determines a variable's type automatically based on what you assign to it. You can check the type at any time using the built-in type() function.
x = 10
print(type(x)) # <class 'int'>
x = "hello"
print(type(x)) # <class 'str'>
x = [1, 2, 3]
print(type(x)) # <class 'list'>
Notice that the same variable name x held an integer, then a string, then a list. Python does not lock a variable to a single type. Each time you reassign, the name simply points to a new object of whatever type you provided.
Variable Naming Rules
Python enforces specific rules about what counts as a valid variable name. Breaking these rules results in a SyntaxError before your program even runs.
- Must start with a letter or underscore. Names like
age,_count, andUserare valid. Names like2fastor@handleare not. - Can only contain letters, digits, and underscores after the first character. The name
score_2works, butscore-2orscore 2will fail. - Case-sensitive. The names
Total,total, andTOTALare three completely different variables. - Cannot be a reserved keyword. Python reserves words like
if,for,class,return, andimportfor its own syntax. Attempting to use them as variable names raises an error.
Avoid shadowing built-in names like list, str, int, type, or id. Assigning to these names replaces the built-in function with your value, which can cause confusing errors later in your program.
Common Assignment Patterns
Python supports several shorthand patterns for assigning variables that you will encounter frequently.
# Multiple assignment on one line
x, y, z = 10, 20, 30
# Assign the same value to multiple variables
a = b = c = 0
# Swap two variables without a temporary variable
x, y = y, x
# Delete a variable from the namespace
del z
# print(z) would now raise a NameError
The swap pattern x, y = y, x is particularly useful and is something Python handles more elegantly than languages that require a temporary holding variable.
How to Store Data in Variables in Python
Follow these three steps to store data in a Python variable. This process works in any Python environment, from a terminal REPL to an IDE like VS Code or PyCharm.
-
Choose a descriptive variable name
Pick a name that describes the data it will hold. Follow Python naming rules: start with a letter or underscore, use only letters, digits, and underscores, and avoid reserved keywords. For example, use
user_ageinstead ofx. -
Use the assignment operator to store a value
Place your variable name on the left side of the equals sign (
=) and the value on the right. Python creates an object for the value in memory and makes your variable name point to it. For example:user_age = 30. -
Verify the stored data using print() and type()
Use
print(user_age)to display the stored value andtype(user_age)to confirm its data type. You can also useid(user_age)to see the memory address of the underlying object. This confirms that your data was stored successfully.
"Namespaces are one honking great idea." — The Zen of Python (PEP 20)
Python Learning Summary Points
- Variables in Python are references (name tags) that point to objects stored on the heap, not containers that hold values directly.
- Python is dynamically typed, so you do not declare types in advance, and the same variable can be reassigned to different types.
- Variable names must start with a letter or underscore, contain only alphanumeric characters and underscores, and must not use reserved keywords.
- The
id()function reveals the memory address of an object, and theiskeyword checks whether two variables point to the same object. - Python reuses objects for small integers (-5 to 256) and certain strings through interning, making memory usage more efficient.
- When no variable references an object, Python's garbage collector reclaims that memory automatically.
Understanding how Python stores data in memory is one of the foundational skills that will help you reason about your programs as they grow in complexity. With variables as your building blocks, you can now store, retrieve, and transform data throughout your Python programs.
Frequently Asked Questions
A variable in Python is a name that references an object stored in memory. When you write age = 25, Python creates an integer object with the value 25 and assigns the name age to point to that object. Variables do not hold values directly; they hold references to objects.
Python stores all objects on a region of memory called the heap. When you create a variable, the variable name acts as a reference that points to the object's memory address on the heap. Python's memory manager handles allocation and deallocation automatically through garbage collection and reference counting.
No. Python is dynamically typed, which means the interpreter determines the type of a variable based on the value assigned to it. You do not need to declare a type before assigning a value. You can even reassign a variable to a value of a different type later in your program.
Variable names must start with a letter (a-z, A-Z) or an underscore (_). After the first character, names can contain letters, digits (0-9), and underscores. Names are case-sensitive, so myVar and myvar are different. You cannot use Python reserved keywords like if, for, class, or return as variable names.
The id() function returns a unique integer that represents the memory address of an object in CPython. You can use id() to check whether two variables reference the same object in memory. If id(a) equals id(b), both variables point to the same underlying object.
Dynamic typing means that the type of a variable is determined at runtime based on its assigned value, rather than being declared in advance. A variable that holds an integer can later be reassigned to hold a string or a list. Python checks types during execution, not before.
Yes. When you assign one variable to another, such as b = a, both names reference the same object. Python does not create a copy of the object. You can verify this by comparing their id() values. For small integers in the range -5 to 256, Python uses a technique called interning that always reuses the same object.
You can remove a variable from the current namespace using the del keyword. For example, del my_variable removes the name my_variable. If no other references point to the object it held, Python's garbage collector will eventually free that memory.
Immutable objects cannot be changed after creation. Integers, floats, strings, and tuples are immutable. Mutable objects can be modified in place. Lists, dictionaries, and sets are mutable. When you reassign an immutable variable, Python creates a new object rather than modifying the existing one.
A Python variable can reference any object type, including integers (int), floating-point numbers (float), strings (str), booleans (bool), lists (list), tuples (tuple), dictionaries (dict), sets (set), NoneType, and custom class instances. Because Python is dynamically typed, the same variable can hold different types at different points in a program.