Lists, Tuples & Sets
📦 Lists, Tuples & Sets
📋 Lists — Mutable, Ordered Sequences
Lists use the same indexing and slicing syntax you already know from strings (Chapter 5) — [start:stop:step], negative indices, all of it.
b = a does not create a second, independent list — it makes b a second name for the exact same list object in memory, since lists are mutable. Modifying b modifies the only list that exists. To get a real independent copy, use b = a.copy() or b = a[:].
🔒 Tuples — Immutable, Ordered Sequences
Tuples exist for data that shouldn't change after creation — coordinates, RGB values, a fixed record returned from a function. Because they're immutable, they can also be used as dictionary keys and set members (Chapter 7 covers dictionaries), which lists cannot.
🎯 Sets — Unordered, Unique Collections
Collections: Go vs Kotlin vs Python
| Concept | Go | Kotlin | Python |
|---|---|---|---|
| Mutable ordered | []T (slice) | MutableList<T> | list |
| Fixed-size ordered | [N]T (array) | List<T> (read-only view) | tuple |
| Unique/unordered | no built-in set — usually map[T]bool | MutableSet<T> | set |
Go's lack of a built-in set type is a real, sometimes-surprising gap coming from Python — reaching for map[T]bool as a workaround is the standard idiom there.
⚡ A First Look at List Comprehensions
A list comprehension builds a new list from an existing sequence in a single, compact expression:
This is a preview, not the full picture — comprehensions get their own dedicated deep dive in Course 2 (dict/set comprehensions, nested comprehensions, and generator expressions). For now, just recognize the pattern: [expression for item in iterable if condition].
list
Mutable, ordered — the everyday, general-purpose collection.
tuple
Immutable, ordered — for fixed data, unpacking, and use as dict keys.
set
Unordered, unique — automatic deduplication and fast membership tests.
List comprehension
[expr for item in iterable if condition] — a compact way to build a list.
💻 Coding Challenges
Challenge 1: Remove Duplicates, Keep Order
Given numbers = [3, 1, 3, 2, 1, 4, 2], produce a new list with duplicates removed but the original first-seen order preserved: [3, 1, 2, 4]. (Hint: a plain set() alone won't preserve order.)
Goal: Understand the real trade-off between sets (fast, unordered) and lists (ordered) firsthand.
Challenge 2: Coordinate Unpacking
Given a list of three tuples, points = [(1, 2), (3, 4), (5, 6)], loop over it and print each point as "x=1, y=2" using tuple unpacking directly in the for loop header.
Goal: Practice tuple unpacking combined with iteration.
Challenge 3: Common Elements
Given two lists, a = [1, 2, 3, 4, 5] and b = [3, 4, 5, 6, 7], use sets to find and print the elements that appear in both, as a sorted list: [3, 4, 5].
Goal: Practice converting lists to sets to use set intersection, then converting back.
🎯 What's Next
Next chapter: Dictionaries — key-value operations, iterating, and dict comprehensions.