Core Data Structures
Lesson 4 of 8
4Core Data Structures
The big pictureList, tuple, dict and set: what separates them, and when the wrong choice is the reason your program is slow.
What the picture shows: A list is a row of slots numbered from zero, and append adds at its end. A dictionary ties each name to a value so you reach it by name.
Map of this part
The concepts in order, click any one to jump to it:
Two ways into the same idea
Data structures are kinds of containers. A list is an ordered shelf you can add to and take from. A tuple is a sealed box that never changes. A dictionary is a phone book: look up a name and get the number at once. A set is a bag that refuses duplicates. The wrong container makes you search the whole shelf for one book.
list is ordered and mutable with O(n) search. tuple is immutable and can be a key. dict is a hash table reaching a key in O(1) on average. set holds unique items with fast membership tests and union and intersection. This difference explains many slow programs.
Before You Start
🔁Loops
for walks through values one at a time.
🧩Functions
You know how to pass a value to a function and take its result.
The Core Idea
A real program handles collections of values, not one value. Lists and dictionaries are the two structures you will use daily, so start with them before the comparison table.
1A list: several values in order
A list is written in square brackets. You reach an item by its position, and counting starts at zero. -1 means the last one, and len gives the count.
fruits = ["apple", "banana", "grape"]
print(fruits[0])
print(fruits[-1])
print(len(fruits))
fruits.append("fig")
print(fruits)
append adds at the end. The list changes in place, which is why it printed with four items after the addition.
2Walk the list
A for loop visits each item in order, just as it visited the numbers of range in the previous part. With numbers you get ready functions: sum, max and sort.
fruits = ["apple", "banana"]
for fruit in fruits:
print("-", fruit)
numbers = [4, 9, 2]
print(sum(numbers), max(numbers), sorted(numbers))
sorted returns a new sorted list and leaves the original alone.
3A dictionary: a name with a value
A dictionary maps a key to a value, in curly braces. You reach a value by its key, not by position. A new pair is added with the same syntax.
ages = {"Sara": 21, "Khalid": 19}
print(ages["Sara"])
ages["Noura"] = 25
print(ages)
print("Khalid" in ages, "Reem" in ages)
in asks: is this key present? It is safer than reading directly, because reading a missing key raises KeyError.
IndexError: list index out of range. The last item is always at len - 1, or simply -1.How It Works, Step by Step: How a dictionary finds a value by name
You write prices["banana"].
Python turns the key into a number with a function called hash.
The number points straight to the slot without visiting the others.
It returns the value, or raises KeyError when the key is missing.
Going deeper
Most real programs revolve around collections of values, not single variables. Choosing the right structure determines your code's efficiency and clarity.
| Structure | Ordered? | Mutable? | Allows duplicates? | Ideal use |
|---|---|---|---|---|
List [] | Yes | Yes | Yes | A list of items that may change (a shopping cart) |
Tuple () | Yes | No | Yes | A fixed collection (an x, y coordinate) |
Set {} | No | Yes | No (unique elements) | Elements with no duplicates and intersection/difference operations |
Dict {k: v} | Yes (3.7+) | Yes | Keys unique | Mapping a key to a value (name → grade) |
## List — a mutable shopping cart
cart = ["apple", "bread"]
cart.append("milk")
print(cart) # ['apple', 'bread', 'milk']
## Tuple — a fixed coordinate that won't change by accident
point = (3, 7)
# point[0] = 9 -> raises TypeError because Tuple is immutable
## Set — merging two friends' interest lists without duplicates
alice_tags = {"python", "sql", "git"}
bob_tags = {"sql", "docker", "python"}
shared = alice_tags & bob_tags # intersection: {'python', 'sql'}
## Dict — mapping a name to a grade
grades = {"Sara": 95, "Omar": 88}
grades["Lina"] = 91 # adding a new item
print(grades.get("Ahmed", "not registered")) # a safe default instead of KeyError
Check your understanding: why can't a List be used as a Dictionary key, while a Tuple can?
Because Dictionary keys must be immutable (Hashable) so that their internal "fingerprint" stays constant for their whole lifetime. A List is mutable so its fingerprint is unstable, while a Tuple is fixed so its fingerprint is guaranteed.
Worked example
counts = {}, and for each name counts[name] = counts.get(name, 0) + 1. get gives zero on first sight instead of KeyError.Myth vs Reality
| Myth | Reality |
|---|---|
| A list works for everything. | Finding an item in a list walks the whole list. If you look things up by name a dictionary is far faster, and for uniqueness use a set. |
| The first item in a list is number 1. | It is 0. A three-item list is numbered 0, 1 and 2, and [3] raises IndexError. |
| A tuple is a lesser list with no use. | It cannot change after it is made, which is exactly what you want for fixed values like coordinates, and it can be a dictionary key. |
Try it yourself
You have items = ["a", "b", "c"]. What does items[len(items)] give?
len(items) is 3, and the available positions are only 0, 1 and 2, so position 3 is outside the list. To reach the last item write items[-1] or items[len(items) - 1]. This is the off-by-one error that will follow you in every language.
Quick Review Flashcards
Check Your Understanding
What is the difference between a list and a set?
A list is ordered and allows repeats; a set has no order and no repeats.
How do you read a dictionary value without crashing when the key is missing?
With d.get("key"), which returns None, or d.get("key", 0) with a fallback.
What does [1, 2, 3][-1] print?
3; a negative index counts from the end.
Resources for this part
Sorted by kind: start with the official docs when you want the precise reference, or with an article or video when you want the explanation first.
Resources for this lesson
Grouped by type. Start with the official docs for precision, or an article or video for the explanation.
Official docs2
Done with this lesson?
Sign in to save your progress.