Programming with Python › Python Setup and First Programs › Day 44
Day 44: 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.
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
- 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 - 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 - 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.
- 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:
- Explain the name-object model of variables (names are tags bound to objects, not boxes that hold values) and connect it to bytes in memory from Day 4
- Identify the core built-in types — int, float, bool, str, NoneType, list, tuple, dict, set — and give a literal and use for each
- Distinguish dynamic typing (types live on objects, checked at run time) from static typing (types declared on names, checked before running)
- Use type() and isinstance() to inspect and test an object's type, and explain when to prefer isinstance
- Predict truthiness for values including the falsy set (None, False, 0, empty containers) and distinguish absent from present-but-empty with is None
- Distinguish mutable from immutable objects using id(), and convert between types safely with int(), float(), and str() while handling ValueError
- Apply PEP 8 snake_case naming conventions and connect clean typing to reliable data pipelines and typed AI inputs and outputs
Prerequisites
- Day 43 — Python installed and runnable (python3 launches the interpreter and REPL)
- Day 4 — data is bytes in memory (this lesson builds the object layer on top of that)
- A terminal and any text editor; no prior Python programming required
Why this matters
-
Aliasing surprises every Python beginner exactly once, and today is that once, deliberately.
-
A tensor is an object with a name bound to it, so every mutation surprise in your training code is this lesson.
-
Truthiness has a sharp edge:
0and""are falsy, so a value that is present but empty fails anif value:test. -
Mutable default arguments and shared-list bugs both come straight from the binding model.
-
Types belong to objects, not to names. Once that lands, a whole class of confusion disappears.
The idea in plain language
-
A name is a label; the object is the thing. They are separate, and the binding between them can change.
-
Assignment binds a name to an object. It does not copy the object.
-
So two names can tag one object, and changing it through either shows through both.
-
The type belongs to the object, checked as the program runs — which is what “dynamically typed” means.
-
Mutability decides whether change is visible elsewhere. That is the property worth sorting types by.
Historical background
-
Python chose objects for everything, from the start. Integers, functions, classes and modules are all objects with a type and an identity.
-
The name-binding model came from that decision. A variable is not a box holding a value; it is a label attached to an object.
-
Languages that use boxes behave differently. In C, assigning copies bytes into storage; in Python, assigning re-points a label.
-
Neither is more correct, but confusing the two is the origin of most aliasing bugs.
-
Type hints arrived in Python 3.5, in 2015, as annotations the interpreter ignores and external tools check.
-
That was deliberate. Adding real static typing would have broken the language; adding optional annotations gave the benefit without the cost.
What it is — and what it is not
A variable is:
- A name in a namespace, bound to an object.
- Rebindable at any time, to an object of any type.
- Untyped itself. The object carries the type.
It is not:
-
Not a container. Nothing is stored “in” a variable; the name points at something stored elsewhere.
-
Not a copy.
b = acreates no new object. -
Not typed.
x: int = 42is a hint for tools, and the interpreter will happily let you rebindxto a string. -
Not the object’s only handle. Any number of names may point at one object, and the object does not know about any of them.
Why it was created and what problems it solves
-
Uniformity. Everything being an object means one set of rules covers integers, functions, classes and modules alike.
-
Cheap assignment. Binding a name is constant-time whatever the object’s size, because nothing is copied.
-
Flexibility. A name can hold anything, which is what makes Python quick to write.
-
The cost is deferred errors. A type mistake surfaces when the line runs, not when the file is read — which is what type hints and mypy exist to claw back.
-
Mutability is the trade-off made explicit. Immutable objects are safe to share; mutable ones are efficient to build up.
How it works
Names, objects, and binding
Running a = [1, 2, 3] does three things in order:
- The object is created — a list with its own type, value and identity.
- The name
ais created in the current namespace, if it did not exist. ais bound to that object. They are connected, and still separate things.
-
b = amakes no new list. Python bindsbto the same object, andid(a)andid(b)come back identical. -
That is aliasing, and it is the most important consequence of the model.
-
Mutating through one name shows through the other:
b.append(4)leavesareading[1, 2, 3, 4]. -
Rebinding is not mutating.
b = "hello"moves theblabel to a new string and leavesapointing at the list.
The core built-in types
| Type | Example | What it holds | Mutable? |
|---|---|---|---|
int | 42, -7 | Whole numbers, unlimited size | No |
float | 3.14, 2.0 | Real numbers with a fractional part | No |
bool | True, False | A truth value; a subtype of int | No |
str | "hello" | Text | No |
NoneType | None | The single “no value” object | No |
list | [1, 2, 3] | An ordered, changeable sequence | Yes |
tuple | (1, 2, 3) | An ordered, fixed sequence | No |
dict | {"a": 1} | Key-to-value lookups | Yes |
set | {1, 2, 3} | Unordered, unique items | Yes |
-
2and2.0are different types despite being equal in value. -
boolis a subtype ofint, soTrue + Trueis2— worth knowing, not worth relying on. -
Noneis not zero, not empty, notFalse. It is its own object, meaning “deliberately no value”.
Dynamic typing
x = 42 # x points at an int
x = "forty-two" # now at a str — perfectly legal
x = [4, 2] # now a list
-
The name never had a type. Each line re-points it.
-
A statically typed language refuses this at compile time, catching whole classes of mistake before the program runs, at the cost of ceremony.
-
Python offers both, optionally.
x: int = 42is ignored by the interpreter and checked by a tool like mypy.
Asking about types
-
type(obj)returns the type:type(42)is<class 'int'>. -
isinstance(obj, T)answers “is this that type, or a subtype?” -
Prefer
isinstancein real code. It understands subtypes —isinstance(True, int)isTrue— and accepts a tuple:isinstance(x, (int, float)). -
Reserve
type()for exploring and printing.
Truthiness
-
Every object can be tested as true or false, not just booleans.
-
Falsy:
False,None, any zero, and any empty container —"",[],{},(),set(). -
Everything else is truthy.
-
So
if items:reads as “if the list has anything in it.” -
The sharp edge: a value that is genuinely present but zero or empty fails that test. When “absent” and “present but empty” differ, write
if value is not None:.
Mutability, and why it matters
-
Immutable:
int,float,bool,str,tuple. Mutable:list,dict,set. -
“Changing” a string makes a new one.
s = s + "s"builds a new object and re-pointss; the original is untouched. -
Changing a list changes the object, which every name pointing at it sees.
-
Watch it with
id(): after string “modification” the id changes; after list mutation it stays the same. -
Immutability is what makes sharing safe; mutability is what makes building up efficient.
An everyday analogy
Luggage labels at a left-luggage office.
| The office | Python |
|---|---|
| A bag in the rack | An object |
| A label tied to it | A name |
| Two labels on one bag | Aliasing |
| Adding something to the bag | Mutating |
| Moving a label to another bag | Rebinding |
| A sealed bag that cannot be opened | An immutable object |
| The bag’s rack position | Its identity, from id() |
-
The label is not the bag. Writing a second label for the same bag does not produce a second bag.
-
Putting something in through one label is visible through the other, because there was only ever one bag.
-
Moving your label elsewhere leaves the other label exactly where it was.
Examples in practice
-
A function that appends to a list argument and surprises the caller, because the list was never copied.
-
if count:skipping a legitimate zero, which is truthiness biting. -
a == btrue whilea is bfalse: equal values, different objects. -
A mutable default argument shared across every call — the classic Python trap, and it is aliasing again.
-
x = 0.1 + 0.2not equalling0.3, which is floats, and the subject of the next lesson.
Implications: security, privacy, performance, scalability, and cost
-
Security: mutable shared state is where concurrency bugs live, and Day 7’s race conditions apply directly once threads share an object.
-
Passing a mutable object to code you do not control hands it the ability to change your data. Pass a copy when that matters.
-
Performance: binding is constant-time, whatever the object’s size. Copying is not, which is why Python avoids copying.
-
Building a string in a loop with
+creates a new object each time, which is quadratic."".join(parts)is the fix. -
Memory: aliasing means one object, not several. A large array passed around costs nothing extra until someone copies it.
-
Cost: an aliasing bug is expensive to find because the symptom appears far from the mutation that caused it.
Alternatives: free, open source, and commercial
| Tool | Type | What it gives you |
|---|---|---|
id(), is | Free, built in | Identity, as distinct from equality |
copy.copy / copy.deepcopy | Free, standard library | A shallow or a full copy when you need one |
dataclasses(frozen=True) | Free, standard library | Immutable structured objects |
tuple, frozenset | Free, built in | Immutable collections |
| mypy, Pyright | Free, open source | Checking type hints before the program runs |
sys.getsizeof | Free, standard library | What an object actually costs |
- Learn the difference between
copyanddeepcopyearly. A shallow copy duplicates the outer container and still shares what is inside it, which is a subtle and common source of the same aliasing surprise.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Name | A label in a namespace |
| Object | The thing in memory, with a type and an identity |
| Binding | The connection between them |
| Aliasing | Two or more names on one object |
| Mutating | Changing the object itself |
| Rebinding | Pointing a name somewhere else |
is vs == | Same object, versus equal value |
When to use it — and when not to
-
Use
isonly forNoneand other singletons. For values, use==. -
Use
isinstancerather thantype()whenever the answer drives behaviour. -
Use immutable types for anything shared, especially as a default argument or a dictionary key.
-
Copy explicitly when you mean to copy.
list(original)orcopy.deepcopy, depending on how deep the sharing goes. -
Do not use a mutable default argument. Use
Noneand create the object inside the function. -
Do not rely on
boolbeing anint. It is true and it is not something to build on. -
Do not test presence with
if value:when zero or empty is a legitimate value.
The AI connection
-
A tensor is an object, and passing it to a function passes the label, not a copy — which is why in-place operations surprise people.
-
In-place operations are marked with a trailing underscore in PyTorch —
add_,clamp_— precisely because mutating a shared tensor is consequential. -
A mutable default argument in a config function silently shares state between experiments, which is a genuinely hard bug to trace.
-
Truthiness catches people on tensors and arrays: an empty batch is falsy, and so is a tensor of zeros in some libraries.
-
Noneas “not computed yet” is a common and correct pattern in model code, and it needsis Nonerather than a truthiness test.
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
Prove aliasing, then prove the difference between mutating and rebinding. Worked through fully in the Day 44 lab directory.
| What you are doing | Command |
|---|---|
| Bind two names to one list | a = [1,2,3]; b = a |
| Prove it is one object | id(a) == id(b) and a is b |
| Mutate through one | b.append(4), then print a |
| Rebind instead | b = "hello", then print a |
| See a string “change” | s = "cat"; print(id(s)); s += "s"; print(id(s)) |
| See a list change | n = [1]; print(id(n)); n.append(2); print(id(n)) |
| Meet truthiness | bool(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
- The string’s id changed; a new object was made.
- The list’s id did not; the same object was altered.
[0]is truthy even though its only element is falsy — the container is not empty.
Validate your work
- You demonstrated aliasing with
id()andis - You showed that mutating differs from rebinding
- You can explain why a string’s id changes and a list’s does not
- You found a value where
if x:andif x is not None:disagree - You used
isinstancewith a tuple of types -
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
Small integers share ids. Python caches
-5to256, soa is bcan beTruefor equal small ints. Do not build on it. -
Short strings may be interned too. Same caveat.
-
isgives a warning with a literal. Use==for values;isis forNone. -
id()values differ between runs. They are addresses, not stable identifiers.
Common mistakes
- Reading
b = aas a copy. - Using
isto compare values. - A mutable default argument.
- Testing presence with truthiness when zero is legitimate.
Practice assignment
-
Write a function that mutates its argument and one that rebinds it, and predict the caller’s result before running either.
-
Build the mutable-default-argument bug on purpose, observe it across three calls, then fix it with
None. -
Find three values where
if x:andif x is not None:disagree. -
Use
copyanddeepcopyon a nested list and demonstrate what shallow copying still shares.
Extension challenge
-
Find Python’s small-integer cache boundary by comparing
ison increasing values, and explain why the boundary exists. -
Measure the cost of string concatenation in a loop against
"".join, for 10,000 items. The ratio is the argument for the idiom. -
Write a function that cannot mutate its argument, by taking a tuple, and discuss what you gave up.
-
Add type hints to a small module and run mypy, then deliberately violate one and confirm the interpreter still runs it while mypy objects.
Quiz
Q1. In Python, what is a variable such as x after you write x = 5?
- A name bound to the integer object 5, which lives in memory
- A box in memory that stores the value 5 inside it
- A reserved slot that can only ever hold integers from now on
- 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, 2, 3] — a is an independent copy and is unaffected
- [1, 2, 3, 4] — a and b are two names for the same list object
- [4] — appending replaces the contents
- 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?
- Every variable must be declared with its type before use
- Types are checked by the compiler before the program runs
- The type belongs to the object and is checked at run time
- 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?
- list, dict, set
- dict, tuple, float
- int, list, str
- 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?
- Raises ValueError; "3.5" is not an integer string
- Returns the integer 4 by rounding
- Returns the integer 3 by truncating
- 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, "a", [0], True
- 0, "", [], None
- "False", -1, [None], {0: 0}
- 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?
- isinstance is faster in every case
- type() does not exist in modern Python
- isinstance understands subtypes and accepts a tuple of types
- 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?
- if value: — because zero counts as no value
- if type(value) == int: — because only integers can be present
- if value == "": — because absent values are empty strings
- 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
- Built-in Types — Python Software Foundation (accessed 2026-07-12)
- An Informal Introduction to Python — Python Software Foundation (accessed 2026-07-12)
- Variables in Python — Real Python (accessed 2026-07-12)
- PEP 8 — Style Guide for Python Code — Python Software Foundation (accessed 2026-07-12)
- Data type — Wikipedia (accessed 2026-07-12)
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.