Thuta Learning
Python
BasicProgrammingBeginner

Python Variables

PythonLesson 625 min

What you'll walk away with

  • Explain how = evaluates the right side first and then binds a name to the object
  • Tell valid from invalid names and follow PEP 8 naming
  • Swap with a, b = b, a and update values with +=
  • Know that b = a does not copy a list, and copy it with .copy()

Explain it simply

Explain it simply

Variables are often described as boxes that hold values, but in Python a better picture is a name tag. When you write age = 25, Python creates the object 25 in memory and ties a tag reading age to it.

A tag can be moved to a different object, and one object can carry several tags. That last point matters for changeable objects such as lists: change the object through one tag and you see the change through every other tag too.

Problem → Why → Solution

The problem: you think you copied, but the original changed

You want Tuesday's shopping list to start from Monday's, so you write tuesday = monday. You add milk to Tuesday's list, and milk appears in Monday's list as well. No error is raised; two pieces of data have quietly merged, and in a large program this kind of bug is very hard to track down.

shopping.py
monday = ["rice", "eggs"]
tuesday = monday            # looks like a copy
tuesday.append("milk")
print(monday)               # ['rice', 'eggs', 'milk'] - Monday changed too!

Why does this happen?

tuesday = monday does not build a new list; it ties a second tag, tuesday, onto the same list object that monday is tied to. .append() changes that single object, so both names show the change. To get an independent list, write tuesday = monday.copy().

Core concept: names refer to objects

In an assignment statement (name = expression), Python evaluates the right side first and then binds the resulting object to the name on the left. That is why count = count + 1, impossible in mathematics, makes sense in Python: "take count's current value, add 1, and attach count to the result". The shorthand is count += 1. No keyword is needed to declare a variable, and using a name before anything has been assigned to it raises a NameError.

One object can have many names. For immutable objects such as int, float, str and tuple this is harmless: x = x + 1 does not modify the old object, it creates a new one and moves x to it, so other names keep pointing at the old value. Mutable objects such as list, dict and set can be changed in place, so after b = a a change made through b is visible through a. To check whether two names share one object, use a is b or compare id(a) == id(b).

The naming rules are strict: only letters, digits and underscores (_), never starting with a digit, never a keyword such as if, for, class or True, and age is not the same as Age. On top of the rules, PEP 8 conventions use snake_case for variables (monthly_total) and UPPER_CASE for values that never change during the program (MAX_RETRIES). Python does not actually protect such constants; UPPER_CASE is an agreement between developers that says "do not reassign this".

You can assign several names in one line. a, b = 1, 2 (unpacking) hands out the right-hand values in order, and a, b = b, a swaps two variables without a temporary one. x = y = 0 binds both names to one object, so doing the same with a list brings back the aliasing problem.

Mental model: name tags on objects
  1. Evaluate the right-hand side
  2. Get the resulting object
  3. Tie the left-hand name to it
  4. A later assignment moves the tag

Assignment never copies an object; if you need a copy, ask for one explicitly with something like .copy().

General pattern: forms of assignment

python
name = expression          # bind a name
name = name + step         # rebind using the old value
name += step               # same thing, shorter
first, second = value_a, value_b   # unpack in order
first, second = second, first      # swap
CONSTANT_NAME = fixed_value        # convention: never reassigned
independent = original.copy()      # a real copy of a list or dict

The left side holds a name, or several comma-separated names; the right side is any expression that produces a value. The last line is how you make a separate copy of a mutable object.

Example: assignment, swapping, dynamic typing and aliases

This example walks through the whole lesson in five parts. In the last part, changing backup also changes scores, so predict the final line before you run it. Printing type(age) directly would show the longer <class 'int'>; here type(...).__name__ prints just the short name.

variables.py
x = 5
name = "Sai"
print(f"x = {x}, name = {name}")

age = 25
height = 5.9
is_student = True
print(type(age).__name__, type(height).__name__, type(is_student).__name__)

a, b = 10, 20
a, b = b, a
print(f"after swap: a = {a}, b = {b}")

my_var = 42
my_var = "now a string"
print(my_var, type(my_var).__name__)

scores = [90, 85]
backup = scores          # a second name for the same list
backup.append(70)
print(scores, backup is scores)

Code breakdown

  1. Lines 1-2name = "Sai"

    Two objects, the int 5 and the str "Sai", are created and the names x and name are tied to them. No type declaration is needed.

  2. Line 8print(type(age).__name__, type(height).__name__, type(is_student).__name__)

    Asks each value for its type: 25 is an int, 5.9 a float and True a bool. The type comes from the value.

  3. Line 11a, b = b, a

    The right side (b, a) is evaluated first, giving (20, 10), and only then are a and b rebound in order. That is why no temporary variable is needed.

  4. Lines 14-15my_var = "now a string"

    The my_var tag moves from the int 42 to a str object. It is allowed, but keeping one type per name makes code easier to follow.

  5. Lines 18-21backup = scores # a second name for the same list

    backup is not a new list but a second tag on the list scores points to. After append(70), scores contains 70 too, and backup is scores is True.

You should see
x = 5, name = Sai
int float bool
after swap: a = 20, b = 10
now a string str
[90, 85, 70] True
Variables & Data Types Visual Guide
Variables and the int, float, str and bool data types, shown visually.

Aliases and copies, drawn out

In the picture below, scores and backup point at one list object, while fresh points at a new list made with .copy(). Changing fresh leaves the other two untouched. The Monday and Tuesday shopping lists from the problem section were in the scores/backup situation; fresh shows the fixed version.

text
names and objects after: backup = scores; fresh = scores.copy()
---------------------------------------------------------------
  names                 objects in memory
  -------               ------------------------------
  scores  ----+
              +------>  [90, 85, 70]    (one list, two names)
  backup  ----+

  fresh   ----------->  [90, 85, 70]    (separate list from .copy())
copy_vs_alias.py
scores = [90, 85, 70]
backup = scores
fresh = scores.copy()

fresh.append(100)
print(scores)            # [90, 85, 70]
print(fresh)             # [90, 85, 70, 100]
print(backup is scores, fresh is scores)   # True False

.copy() is a shallow copy

.copy() builds a new outer list only. If the list contains other lists, those inner lists are still shared by both; for nested data like that, use copy.deepcopy() from the copy module.

In real projects

Where this shows up in real projects

Almost every project gathers configuration values at the top of a file as UPPER_CASE constants, such as DATABASE_URL, MAX_UPLOAD_MB or TIMEOUT_SECONDS. Because the numbers have names instead of being scattered through the code, changing one means editing a single place. Putting the unit in the name (timeout_seconds, price_kyat) prevents bugs such as mixing up minutes and seconds.

Aliasing bugs are common in web applications. If each user's settings start as settings = DEFAULTS and are then modified, one user's change leaks into every user after them; settings = DEFAULTS.copy() fixes it. In data analysis, modifying a pandas DataFrame without .copy() can change the original data too, so this lesson's name-tag picture is useful everywhere.

Common mistakes

Common mistakes

1. Treating b = a as a copy

For lists and dicts, b = a only creates an alias. When you need separate data, use b = a.copy() (or list(a), dict(a)), and copy.deepcopy(a) for nested data.

2. Using built-in names as variables

list = [1, 2] or sum = 0 raises no error, but it hides the built-in list() and sum(). A later sum([1, 2]) then fails with "TypeError: 'int' object is not callable". Use names such as numbers or total.

3. Using a name before assigning it

Running total += price before total = 0 exists raises a NameError, because += must read the old value first. Always give counters and totals a starting value before the loop.

Best practices

Best practices

  • Prefer names that describe meaning, such as unpaid_invoices or retry_count, over x, tmp or data2.
  • Put the unit into numeric names: delay_seconds, weight_kg, price_kyat.
  • Name booleans as yes/no questions, such as is_active or has_paid.
  • If a function modifies a list it receives, say so in its docstring because the caller's data changes; otherwise work on a copy.

Mini challenge

Mini challenge: a shopping basket

Build your own basket from a default basket without changing the default, then print the item count, a swap and a total with tax.

  • Define TAX_RATE = 0.05 as an UPPER_CASE constant
  • Make my_basket a copy of default_basket and add "tea"; default_basket must not change
  • Start item_count at 0 and update it with +=
  • Put the first and last items into two variables and swap them in one line
basket.py
# TODO: TAX_RATE constant
default_basket = ["rice", "oil"]

# TODO: my_basket = an independent copy of default_basket, then add "tea"
# TODO: item_count starts at 0, then += the number of items in my_basket
# TODO: first, last = the first and last items; swap them in one line

# TODO: print both baskets to prove default_basket is unchanged
# TODO: print item_count and the swapped pair
subtotal = 12000
# TODO: print subtotal with tax, rounded to a whole number

Expected: Expected output: default: ['rice', 'oil'] mine: ['rice', 'oil', 'tea'] items: 3, swapped: tea / rice total with tax: 12600

Show hint

my_basket[0] is the first item and my_basket[-1] the last. f"{value:.0f}" prints a number with no decimals.

Show solution
basket.py
TAX_RATE = 0.05
default_basket = ["rice", "oil"]

my_basket = default_basket.copy()
my_basket.append("tea")
item_count = 0
item_count += len(my_basket)
first, last = my_basket[0], my_basket[-1]
first, last = last, first

print("default:", default_basket)
print("mine:", my_basket)
print(f"items: {item_count}, swapped: {first} / {last}")
subtotal = 12000
print(f"total with tax: {subtotal * (1 + TAX_RATE):.0f}")

Quick quiz 1 / 3

After a = [1, 2], b = a and b.append(3), what does print(a) show?

Quick quiz 2 / 3

Which of these is a valid Python variable name?

Quick quiz 3 / 3

After x = 5, y = x and x = x + 1, what does print(y) show?

What to remember

  • A variable is a name tag on an object; = evaluates the right side first, then binds.
  • Names use letters, digits and _, cannot start with a digit or be a keyword, and are case-sensitive.
  • Use snake_case for variables and UPPER_CASE for constants, and do not shadow built-in names.
  • a, b = b, a swaps values and += updates a value from its old one.
  • b = a never copies a mutable object; use .copy().

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Variables | Thuta Learning