Programming with Python › Python Setup and First Programs › Day 44

Day 44: Variables and Types

Day 44 of 365 — Variables and Types

After this lesson you will be able to explain what a Python variable really is — a name bound to an object — name the core built-in types, tell mutable from immutable, and convert between types safely, so type confusion never silently breaks your data or model code.

Course
Programming with Python
Category
Python Setup and First Programs
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/programming-with-python/day-044-variables-and-types

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/programming-with-python/day-044-variables-and-types
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language

Diagram: variables as boxes compared with variables as labels


Historical background


What it is — and what it is not

A variable is:

It is not:


Why it was created and what problems it solves


How it works

Names, objects, and binding

Diagram: mutating an object compared with rebinding a name

Diagram: the three steps of a Python assignment

Diagram: two names bound to the same object in memory, illustrating aliasing in Python

Running a = [1, 2, 3] does three things in order:

  1. The object is created — a list with its own type, value and identity.
  2. The name a is created in the current namespace, if it did not exist.
  3. a is bound to that object. They are connected, and still separate things.

The core built-in types

TypeExampleWhat it holdsMutable?
int42, -7Whole numbers, unlimited sizeNo
float3.14, 2.0Real numbers with a fractional partNo
boolTrue, FalseA truth value; a subtype of intNo
str"hello"TextNo
NoneTypeNoneThe single “no value” objectNo
list[1, 2, 3]An ordered, changeable sequenceYes
tuple(1, 2, 3)An ordered, fixed sequenceNo
dict{"a": 1}Key-to-value lookupsYes
set{1, 2, 3}Unordered, unique itemsYes

Diagram: the core Python built-in types grouped by mutability and by category

Dynamic typing

Diagram: how Python type hints are checked

x = 42          # x points at an int
x = "forty-two" # now at a str — perfectly legal
x = [4, 2]      # now a list

Asking about types

Truthiness

Diagram: which Python values are falsy

Mutability, and why it matters

Diagram: immutable Python types compared with mutable ones


An everyday analogy

Luggage labels at a left-luggage office.

The officePython
A bag in the rackAn object
A label tied to itA name
Two labels on one bagAliasing
Adding something to the bagMutating
Moving a label to another bagRebinding
A sealed bag that cannot be openedAn immutable object
The bag’s rack positionIts identity, from id()

Examples in practice

Diagram: how a mutable default argument shares state between calls


Implications: security, privacy, performance, scalability, and cost


Alternatives: free, open source, and commercial

Diagram: assignment compared with shallow and deep copying

ToolTypeWhat it gives you
id(), isFree, built inIdentity, as distinct from equality
copy.copy / copy.deepcopyFree, standard libraryA shallow or a full copy when you need one
dataclasses(frozen=True)Free, standard libraryImmutable structured objects
tuple, frozensetFree, built inImmutable collections
mypy, PyrightFree, open sourceChecking type hints before the program runs
sys.getsizeofFree, standard libraryWhat an object actually costs

Diagram: identity comparison compared with equality comparison

TermWhat it actually is
NameA label in a namespace
ObjectThe thing in memory, with a type and an identity
BindingThe connection between them
AliasingTwo or more names on one object
MutatingChanging the object itself
RebindingPointing a name somewhere else
is vs ==Same object, versus equal value

When to use it — and when not to


The AI connection


Knowledge check

quiz:
  question: "A function receives a list, appends an item to it, and returns nothing. The caller's own list has changed. Why?"
  options:
    - "The parameter is a second name bound to the same list object, so mutating through it is visible everywhere"
    - "Python passes arguments by reference only for lists, and by value for other types"
    - "The function's local scope was not isolated because it returned nothing"
    - "Lists are copied on assignment but not when passed as arguments"
  answer_index: 0
  explanation: "Passing an argument binds a new name to the same object; no copying occurs for any type. Because a list is mutable, appending changes the one object both names point at — while rebinding the parameter inside the function would have changed nothing for the caller."

Hands-on exercise

Diagram: how id() reveals whether an object was mutated or replaced

Prove aliasing, then prove the difference between mutating and rebinding. Worked through fully in the Day 44 lab directory.

What you are doingCommand
Bind two names to one lista = [1,2,3]; b = a
Prove it is one objectid(a) == id(b) and a is b
Mutate through oneb.append(4), then print a
Rebind insteadb = "hello", then print a
See a string “change”s = "cat"; print(id(s)); s += "s"; print(id(s))
See a list changen = [1]; print(id(n)); n.append(2); print(id(n))
Meet truthinessbool(0), bool(""), bool([]), bool([0])

Expected output

True True
[1, 2, 3, 4]
[1, 2, 3, 4]
4404445184  4404589424
4404512320  4404512320
False False False True

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. In Python, what is a variable such as x after you write x = 5?

  1. A name bound to the integer object 5, which lives in memory
  2. A box in memory that stores the value 5 inside it
  3. A reserved slot that can only ever hold integers from now on
  4. A copy of the number 5 that is separate from the original
Show answer

Answer: A. A name bound to the integer object 5, which lives in memory

A Python variable is a name bound to an object, not a container. Writing x = 5 ties the name x to the already-existing integer object 5; the object holds the type, value, and identity, while the name is just a tag.

Q2. After a = [1, 2, 3] and b = a, you run b.append(4). What does a now refer to?

  1. [1, 2, 3] — a is an independent copy and is unaffected
  2. [1, 2, 3, 4] — a and b are two names for the same list object
  3. [4] — appending replaces the contents
  4. It raises an error because you cannot change a shared list
Show answer

Answer: B. [1, 2, 3, 4] — a and b are two names for the same list object

b = a makes a second name for the same object (aliasing), it does not copy. Because the list is mutable, appending through b changes the one shared object, so a sees [1, 2, 3, 4] too.

Q3. Which statement best describes dynamic typing in Python?

  1. Every variable must be declared with its type before use
  2. Types are checked by the compiler before the program runs
  3. The type belongs to the object and is checked at run time
  4. A variable keeps the type of the first value assigned to it forever
Show answer

Answer: C. The type belongs to the object and is checked at run time

Python is dynamically typed: the type lives on the object, not the name, and is checked as the program runs. A name like x can be re-bound from an int to a str to a list freely — the name itself is untyped.

Q4. Which of these groups lists only IMMUTABLE Python types?

  1. list, dict, set
  2. dict, tuple, float
  3. int, list, str
  4. int, str, tuple
Show answer

Answer: D. int, str, tuple

int, str, and tuple are all immutable — once created, their value cannot change in place. list, dict, and set are mutable. "Changing" an immutable object always produces a new object and re-points the name.

Q5. What does int("3.5") do in Python?

  1. Raises ValueError; "3.5" is not an integer string
  2. Returns the integer 4 by rounding
  3. Returns the integer 3 by truncating
  4. Returns the float 3.5 unchanged
Show answer

Answer: A. Raises ValueError; "3.5" is not an integer string

int() on a string only accepts a valid whole-number string, so int("3.5") raises ValueError. To truncate you must go through the float first: int(float("3.5")) gives 3. (int(3.9) on a float does truncate to 3.)

Q6. Which list contains only FALSY values?

  1. 1, "a", [0], True
  2. 0, "", [], None
  3. "False", -1, [None], {0: 0}
  4. 0.1, " ", (0,), {None}
Show answer

Answer: B. 0, "", [], None

The falsy values are False, None, any zero (0, 0.0), and any empty container ("", [], {}, (), set()). Note that "False" is a non-empty string and therefore truthy, and (0,) is a non-empty tuple and also truthy.

Q7. Why should you usually prefer isinstance(x, int) over type(x) == int for type checks?

  1. isinstance is faster in every case
  2. type() does not exist in modern Python
  3. isinstance understands subtypes and accepts a tuple of types
  4. type() returns a string while isinstance returns a real type
Show answer

Answer: C. isinstance understands subtypes and accepts a tuple of types

isinstance() returns True for subtypes (for example isinstance(True, int) is True because bool is a subtype of int) and accepts a tuple like (int, float) to test several types at once. type() reports only the exact type and is best reserved for exploration and printing.

Q8. You need to tell "no value was provided" apart from "the value is zero." Which test is correct?

  1. if value: — because zero counts as no value
  2. if type(value) == int: — because only integers can be present
  3. if value == "": — because absent values are empty strings
  4. if value is not None: — None means absent, 0 is present
Show answer

Answer: D. if value is not None: — None means absent, 0 is present

Because 0 is falsy, if value: cannot distinguish a genuine 0 from an absent value. None is the object that means "no value," and there is exactly one of it, so if value is not None: is the correct and idiomatic test for presence.

Glossary

variable
A name that refers (is bound) to an object. In Python a variable is a tag on an object, not a box that stores a value.
object
A thing in memory that carries a type, a value, and an identity. In Python everything — numbers, text, lists, even types — is an object.
binding
The link between a name and the object it refers to, created by assignment (name = object). Re-binding moves the name to a different object.
aliasing
The situation where two or more names refer to the same object, so a change made through one name is visible through the others (relevant for mutable objects).
dynamic typing
The rule that a value's type belongs to the object and is checked at run time, so a name may be re-bound to a value of any type at any point.
static typing
The alternative approach, used by languages like Java, where a variable's type is declared in advance and checked before the program runs.
int
The integer type: whole numbers of unlimited size, such as 42, 0, and -7. Immutable.
float
The floating-point type: real numbers with a fractional part, such as 3.14 and 2.0. Immutable, and distinct from int even when the value looks whole.
bool
The boolean type with the two values True and False. A subtype of int, so True behaves as 1 and False as 0 in arithmetic. Immutable.
str
The string type: text as a sequence of characters, such as "hello". Immutable, so "changing" a string produces a new object.
NoneType
The type of the single object None, which represents the deliberate absence of a value — distinct from 0, "", and False.
mutable
Describes an object that can be changed in place after creation, keeping the same identity. list, dict, and set are mutable.
immutable
Describes an object that cannot be changed after creation; "modifying" it creates a new object. int, float, bool, str, and tuple are immutable.
truthiness
The rule that any object can be treated as true or false in a condition. Falsy values are False, None, any zero, and any empty container; everything else is truthy.
type conversion
Turning a value of one type into another by calling the target type, such as int("42"), float("3.14"), or str(42). Can raise ValueError on invalid input.
identity
A permanent, per-object marker of "which object is this," returned by id(). In the standard interpreter it is essentially the object's memory address; the is operator compares it.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.