Lists, Tuples & Sets

Python Fundamentals
Course 1 ยท Chapter 6 ยท Lists, Tuples & Sets

๐Ÿ“ฆ Lists, Tuples & Sets

Python has three built-in collection types worth knowing apart from day one: lists (mutable, ordered), tuples (immutable, ordered), and sets (unordered, unique). This chapter covers all three, plus a first look at list comprehensions โ€” a compact way to build a list from an existing sequence.

๐Ÿ“‹ Lists โ€” Mutable, Ordered Sequences

fruits = ["apple", "banana", "cherry"]

fruits.append("date")      # ['apple', 'banana', 'cherry', 'date']
fruits.insert(1, "apricot") # insert at a specific index
fruits.remove("banana")     # removes the first matching value
last = fruits.pop()          # removes and returns the last item
fruits.sort()                # sorts in place, alphabetically

print(fruits[0])       # indexing and slicing work exactly like strings
print(fruits[1:])

Lists use the same indexing and slicing syntax you already know from strings (Chapter 5) โ€” [start:stop:step], negative indices, all of it.

โš  Assigning a List Copies the Reference, Not the List
a = [1, 2, 3]
b = a          # b now points to the SAME list as a
b.append(4)
print(a)      # [1, 2, 3, 4] โ€” a changed too!

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

point = (3, 7)
print(point[0])   # 3 โ€” indexing works like a list

# point[0] = 5   # TypeError โ€” tuples can't be modified after creation

# Tuple unpacking โ€” a very common Python idiom
x, y = point
print(x, y)   # 3 7

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

numbers = {1, 2, 2, 3, 3, 3}
print(numbers)          # {1, 2, 3} โ€” duplicates automatically removed

a = {1, 2, 3}
b = {2, 3, 4}

print(a | b)   # {1, 2, 3, 4} โ€” union
print(a & b)   # {2, 3} โ€” intersection
print(a - b)   # {1} โ€” difference

print(3 in a)    # True โ€” membership tests on sets are very fast

Collections: Go vs Kotlin vs Python

ConceptGoKotlinPython
Mutable ordered[]T (slice)MutableList<T>list
Fixed-size ordered[N]T (array)List<T> (read-only view)tuple
Unique/unorderedno built-in set โ€” usually map[T]boolMutableSet<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:

numbers = [1, 2, 3, 4, 5]

# The loop version, from Chapter 4:
squares = []
for n in numbers:
    squares.append(n ** 2)

# The comprehension version โ€” same result, one line:
squares = [n ** 2 for n in numbers]

# With a filtering condition:
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
print(even_squares)   # [4, 16]
๐Ÿ’ก Just a First Look

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.

โ†’ Solution

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.

โ†’ Solution

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.

โ†’ Solution

๐ŸŽฏ What's Next

Next chapter: Dictionaries โ€” key-value operations, iterating, and dict comprehensions.