Free Handbook · Runs in your browser

Data Types

Numbers and the math module, strings and their methods, then the four containers — lists, tuples, sets and dictionaries — with the IndexError, KeyError and tuple-mutation errors each one hands you, and a guide to choosing the right one.

0 / 108 lessons🔥 0 day streak
ShareXLinkedIn

Module 03 · what you'll be able to do

  • Use int, float, the math module and know where floats lie to you
  • Slice, search, split, join and format strings
  • Build, index, slice and mutate lists; sort them by any key
  • Know why tuples exist and when a set beats a list
  • Use dictionaries as the workhorse they are, with .get(), .items() and setdefault
  • Pick the right container for a problem in seconds
01

Numbers and math

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
0.30000000000000004
False
True
2.67
0.3
4.0 3.141592653589793 3 4
4 9 2 6
(3, 2)
100000000000000000000
3.5 3 3
Your turn
Compute compound interest: 1000 at 5% for 10 years, rounded to 2 decimals. Then do it with Decimal and compare.
Never store money in a float
0.1 + 0.2 != 0.3 is not a Python bug; it is how binary floating point works in every language. For money use integer cents or Decimal. Interviewers ask about this.
02

Strings

Strings are sequences of characters, and immutable: every method returns a new string and the original never changes. That is why s.upper() on its own does nothing visible — you have to keep the result.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
H d Hello World dlroW ,olleH
HELLO, WORLD hello, world Hello, World
Hello, Python
7 -1
True True False
padded|
12 3
['data', 'engineering', 'is', 'fun']
data-engineering-is-fun
['2026', '09', '20']
65 B
Your turn
Check whether "A man, a plan, a canal: Panama" is a palindrome — lowercase it, keep only letters (c.isalpha()), compare with its reverse.
Error you will hit

TypeError: 'str' object does not support item assignment

python
word = "cat"
word[0] = "b"
Traceback (most recent call last):
  File "your code", line 2, in <module>
    word[0] = "b"
TypeError: 'str' object does not support item assignment
Why the interpreter said that

Strings cannot be changed in place. This is what immutable means — and it is a feature: it lets strings be dictionary keys and be shared safely.

The fix

Build a new string, with slicing or replace, and rebind the name.

python
word = "cat"
word = "b" + word[1:]
print(word)   # bat
Immutable
Cannot be changed after creation. str, int, float, bool, tuple and frozenset are immutable; list, dict and set are mutable.
Slice
seq[start:stop:step]. Any part can be omitted. seq[::-1] reverses; seq[:] copies. Never raises for out-of-range bounds — it just clips.
03

Lists

A list is an ordered, mutable sequence of anything. It is the container you reach for by default, and most of its methods change it in place and return None — the source of the result = items.append(x) surprise from Module 00.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
[7, 4, 1, 3, 9, 2, 8]
8
[7, 4, 3, 9, 2] 5
7 2 [4, 3]
True 3
[2, 3, 4, 7, 9]
[9, 7, 4, 3, 2]
[('Linus', 28), ('Ada', 36), ('Grace', 45)]
[1, 2, 3, 4] [1, 2, 3]
Your turn
Given scores = [88, 92, 79, 93, 85], print the top two and the average to one decimal.
Error you will hit

IndexError: list index out of range

python
items = ["a", "b", "c"]
for i in range(1, 4):
    print(items[i])
b
c
Traceback (most recent call last):
  File "your code", line 3, in <module>
    print(items[i])
IndexError: list index out of range
Why the interpreter said that

Valid indexes for a 3-item list are 0, 1, 2 (and -1, -2, -3). The loop asked for items[3]. Almost every IndexError is an off-by-one: a range that ends at len(items) instead of len(items) - 1, or the belief that indexes start at 1.

The fix

Loop over the list itself, or over range(len(items)), or use enumerate. You almost never need to compute an index by hand.

python
items = ["a", "b", "c"]
for i, item in enumerate(items):
    print(i, item)
Aliasing is the second-most common list bug
b = a makes two names for one list; changing one changes "both". a[:], list(a) or a.copy() make a real copy — one level deep. For nested lists use copy.deepcopy.
04

Tuples

A tuple is an immutable list. That sounds like a limitation and is actually the point: a tuple says "this is a fixed record — a coordinate, a date, a (name, score) pair — not a collection you add to". Because it cannot change, it can be a dictionary key or a set member; a list cannot.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
3 4 3 2
tuple int
5
2 9
Ada 36 User(name='Ada', age=36)
Error you will hit

TypeError: 'tuple' object does not support item assignment

python
rgb = (255, 128, 0)
rgb[1] = 200
Traceback (most recent call last):
  File "your code", line 2, in <module>
    rgb[1] = 200
TypeError: 'tuple' object does not support item assignment
Why the interpreter said that

Same family as the string error: tuples are immutable. You chose a tuple (or a function returned one) and are treating it as a list.

The fix

If it should change, make it a list. If it is a record, build a new tuple.

python
rgb = (255, 128, 0)
rgb = (rgb[0], 200, rgb[2])
print(rgb)
05

Sets

A set is an unordered collection of unique items with instant membership tests. Two jobs: de-duplicating, and asking "is X in here?" thousands of times — a list answers that by scanning every element, a set answers in constant time. Set algebra (union, intersection, difference) is the bonus.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
['python', 'spark', 'sql'] 3
repeat: the
repeat: and
repeat: the
{1, 2, 3, 4, 5}
{3, 4}
{1, 2}
{1, 2, 5}
True
[3, 1, 2]
dict set

Set order is not guaranteed — print a set directly and the items may come out in any order. Never rely on it.

Quick check

You have 100,000 user IDs and need to check 50,000 incoming IDs against them. Which container for the 100,000?

06

Dictionaries

A dictionary maps keys to values. It is the most important container in Python — JSON is a dict, a database row is a dict, function keyword arguments are a dict, an object's attributes are a dict. Keys must be immutable (str, int, tuple); values can be anything. Since Python 3.7 dicts remember insertion order.

pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
Ada
None
n/a
True 4
name   Ada
age    37
langs  ['python', 'sql']
['name', 'age', 'langs'] ['Ada', 37, ['python', 'sql']]
{'a': 3, 'b': 2, 'c': 1}
{'data': ['Ada', 'Grace'], 'infra': ['Linus']}
{'theme': 'light', 'lang': 'fr'}
{0: 0, 1: 1, 2: 4, 3: 9}
Your turn
Invert a dictionary: from {"a": 1, "b": 2} make {1: "a", 2: "b"} with a comprehension.
Error you will hit

KeyError: 'phone'

python
user = {"name": "Ada"}
print(user["phone"])
Traceback (most recent call last):
  File "your code", line 2, in <module>
    print(user["phone"])
KeyError: 'phone'
Why the interpreter said that

Square brackets demand the key exist. The error names the missing key — read it; it is often a typo ("Name" vs "name") or data that is sometimes missing (an optional JSON field).

The fix

.get(key, default) when missing is normal; in to check first; or let it raise when a missing key really is a bug — a KeyError that points at the problem beats a silent None that surfaces three functions later.

python
user = {"name": "Ada"}
print(user.get("phone", "no phone on file"))
07

Choosing the right one

You need…UseBecause
An ordered collection you will add to, index, or sortlistMutable, ordered, indexable
A fixed record of a few fields (a point, a row, a pair)tuple / namedtupleImmutable, hashable, signals "this does not grow"
Uniqueness or fast "is it in here?"setO(1) membership, dedupe for free
A lookup from key to value; anything JSON-shapeddictO(1) lookup, ordered, the shape of most data
Counting thingscollections.CounterA dict with .most_common()
A queue (add at one end, remove at the other)collections.dequeO(1) at both ends; a list is O(n) at the front
pythonEdit it. ⌘/Ctrl + Enter runs.
You should see
[('the', 2), ('cat', 2)]
z deque(['a', 'b', 'c'])
Quick check

You are reading a log and need, for each user ID, the list of pages they visited in order. Which shape?

Finish the Python handbook, then get hired

Sit the exam for your certificate, run your resume through the ATS checker, and see the jobs that ask for exactly this.

Check my resume
Found this course useful? Share it.
ShareXLinkedIn

Comments

0

Join the conversation. Sign in to leave a comment — we'd love to hear your thoughts.