Python Variables and Assignment: Names, Values, and Rebinding
In Python, a variable is a name that points to an object, not a box that stores the value itself. The = sign assigns a name to an object, and later assignments can rebind that name to a different object. This article shows how assignment really works, how it behaves with mutable values, and how to avoid the mistakes that confuse beginners.
Difficulty: Beginner
Helpful to know first: Basic Python syntax, how to run a script, and the difference between a value and a name.
How Python Assignment Really Works
Python assignment does not copy a value into a storage slot the way many first-time programmers expect. Instead, the assignment statement connects a name on the left side to an object on the right side.
That means this code creates a name called age and binds it to the integer object 19:
age = 19
print(age) # Output: 19The important part is that age is a name. If you later assign a different object to the same name, Python updates the binding.
age = 19
age = 20
print(age) # Output: 20This is called rebinding. The name age now refers to a new integer object.
Multiple Names Can Refer to the Same Object
One value can have more than one name pointing to it. This is a big part of Python's behavior with mutable objects such as lists and dictionaries.
Simple aliasing with a list
Here, both names point to the same list object:
numbers = [1, 2, 3]
alias = numbers
alias.append(4)
print(numbers) # Output: [1, 2, 3, 4]
print(alias) # Output: [1, 2, 3, 4]Both numbers and alias refer to the same list, so changing the list through one name changes what the other name sees.
Why this matters for mutable and immutable objects
Some objects, like integers, strings, and tuples, cannot be changed in place. Others, like lists and dictionaries, can. That difference changes how assignment feels in practice.
x = 10
y = x
x = x + 1
print(x) # Output: 11
print(y) # Output: 10Here, x is rebound to a new integer object. The name y still points to the original 10.
Common Ways to Use Assignment in Real Code
Storing input for later use
A variable usually stores a result so you can use it more than once.
name = input("What is your name? ")
print("Hello,", name)
# If the user types Ada, output is:
# Hello, AdaThis is the basic pattern for reading a value once and using it multiple times.
Updating a counter
Assignment is often used to replace a variable with a new value based on its old value.
count = 0
count = count + 1
print(count) # Output: 1Python also supports a shorter version for common updates, such as count += 1. The meaning is still assignment: the name gets rebound to a new value.
Swapping values cleanly
Python can swap names without a temporary variable.
left = "apple"
right = "orange"
left, right = right, left
print(left) # Output: orange
print(right) # Output: appleThe right-hand side is evaluated first, then the names on the left are assigned. This is one reason Python's assignment feels different from many other languages.
Assignment, Rebinding, and Copying Are Not the Same
Beginners often expect b = a to make a new independent copy. That is not what plain assignment does.
With immutable objects, the difference is less visible because you cannot change the object itself. With mutable objects, it matters immediately.
a = [1, 2]
b = a
b.append(3)
print(a) # Output: [1, 2, 3]
print(b) # Output: [1, 2, 3]If you need a separate list, make one explicitly.
a = [1, 2]
b = a.copy()
b.append(3)
print(a) # Output: [1, 2]
print(b) # Output: [1, 2, 3]The first version shares one list between two names. The second version creates a new list object, so changes to b do not affect a.
How Python Handles Assignment in Detail
Python evaluates the right side of an assignment before it binds the result to the left side. That order is important when the right side depends on current values.
For example, in x = x + 1, Python reads the old value of x, adds 1, and then rebinds x to the new integer.
Python also allows multiple assignment and unpacking. The number of names on the left must match the number of values on the right, unless you use starred unpacking.
first, second = 10, 20
print(first) # Output: 10
print(second) # Output: 20If the counts do not match, Python raises an error at runtime.
first, second = [1]
# ValueError: not enough values to unpack (expected 2, got 1)That message means Python found fewer values than names expected.
Assignment in Python is a statement, not an expression. You do not use it to produce a value inside another expression the way some languages allow.
Predict the Output
Aliasing a list and changing it through one name
What does this print?
items = [1, 2]
copy = items
copy.append(3)
print(items)Show answer
It prints [1, 2, 3].
copy and items refer to the same list object. Appending through one name changes the shared list, so the other name sees the updated contents too.
Rebinding after a calculation
What does this print?
x = 5
y = x
x = x + 2
print(y)Show answer
It prints 5.
y was bound to the original integer object before x was rebound. Integers are immutable, so x = x + 2 creates a new integer object and gives x a new binding.
Find the Bug
Find the bug in this code. It looks like it should keep a separate history of scores, but it does not.
def add_score(score, history=[]):
history.append(score)
return history
print(add_score(10))
print(add_score(20))Show answer
The bug is the default list. Default argument objects are created once, not every time the function runs. That means both calls share the same list.
On the first call, the list becomes [10]. On the second call, the same list is reused, so it becomes [10, 20].
Fixed code:
def add_score(score, history=None):
if history is None:
history = []
history.append(score)
return historyThis works because a new list is created only when the caller does not pass one in.
Common Mistakes When Using Variables and Assignment
Expecting assignment to copy a mutable object
New programmers often think b = a makes a separate list or dictionary. It does not. Both names can point to the same object.
Problem: The code changes the list through b and expects a to stay unchanged, but both names refer to the same list.
a = [1, 2]
b = a
b.append(3)
print(a)Fix: Make an explicit copy when you want independent data.
a = [1, 2]
b = a.copy()
b.append(3)
print(a) # Output: [1, 2]The corrected version works because the two names point to different list objects.
Using a variable before it has been assigned
If you read a name before Python has bound it in the current scope, you get an error.
Problem: Python cannot use total because no value has been assigned to that name yet.
print(total)
total = 5Fix: Assign the name before you use it.
total = 5
print(total) # Output: 5The corrected version works because the name exists before Python tries to read it.
Confusing assignment with comparison
Beginners sometimes write an assignment where they meant to compare two values. In Python, comparison uses ==, not =.
Problem: This code is invalid because = is for assignment, not for testing whether two values are equal.
if name = "Ada":
print("Hello")Fix: Use == when you want to compare values.
if name == "Ada":
print("Hello")The corrected version works because == produces a Boolean result that if can test.
When to Rebind a Name and When to Make a New Object
Assignment is the right tool when you want a name to refer to a new value. Copying is better when you want a new independent object. That choice matters most with lists, dictionaries, and sets.
| Situation | Use assignment | Use a copy |
|---|---|---|
| New name for the same object | Yes | No |
| Independent list or dictionary | No | Yes |
| Updating a counter or total | Yes | No |
| Passing shared mutable data on purpose | Yes | No |
For example, use assignment when you want to rename a result for readability:
raw_price = 19.99
price = raw_priceUse copying when later changes should not affect the original object:
original = [1, 2, 3]
backup = original.copy()Interview Questions About Python Variables
What is the difference between a variable and a value in Python?
A value is an object such as 5 or "hello". A variable is a name that refers to that object. The name can be rebound to a different object later.
Why does changing a list through one variable affect another variable?
Because both variables may point to the same list object. If the object is mutable, changing it through one name changes the shared object for every name that refers to it.
Why does x = x + 1 work?
Python reads the current value of x, adds 1, and then rebinds x to the new result. It does not change the old integer object in place.
Try It Yourself
Write a small program that:
- Creates a variable named temperature_c with the value 22.
- Creates a second variable named temperature_f by converting Celsius to Fahrenheit using temperature_c * 9 / 5 + 32.
- Prints both values.
- Rebinds temperature_c to 25 and prints both variables again.
Expected output:
22 C = 71.6 F
25 C = 71.6 FHint: The Fahrenheit value should be stored before you change temperature_c.
Show solution
temperature_c = 22
temperature_f = temperature_c * 9 / 5 + 32
print(temperature_c, "C =", temperature_f, "F")
temperature_c = 25
print(temperature_c, "C =", temperature_f, "F") # Output: 22 C = 71.6 F / 25 C = 71.6 FSummary
- In Python, a variable is a name that refers to an object.
- = binds a name to a value; it does not mean mathematical equality.
- Assignment usually rebinds a name instead of changing the old object.
- Two names can point to the same mutable object, so changes through one name can affect the other.
- Use an explicit copy when you want independent data.
- Use == to compare values, not =.
Next, learn about data types and how Python decides what operations each value supports.