← Back to Programming

Lists, tuples, and dictionaries

Real programs handle collections of data. Python's built-in lists, tuples, sets, and dictionaries cover most everyday needs.

Lists

A list is an ordered, changeable collection: scores = [72, 85, 90]. Items are accessed by index starting at 0, so scores[0] is 72, and negative indexes count from the end, so scores[-1] is 90. len(scores) gives 3. Lists can hold mixed types, though usually they hold one kind of item.

Changing lists

append adds an item to the end; insert adds at a position; remove deletes the first matching value; pop removes and returns an item, by default the last. sort() sorts in place, while sorted() returns a new sorted list. Because lists are mutable, two names can refer to the same list, so changing it through one name changes what the other sees.

Slicing

Slicing extracts part of a sequence: scores[1:3] gives items at indexes 1 and 2. Omitted bounds mean 'from the start' or 'to the end': scores[:2] and scores[1:]. A step can be added: scores[::2] takes every second item, and scores[::-1] reverses the list. Slicing works on strings too.

List comprehensions

A list comprehension builds a list concisely: squares = [n * n for n in range(1, 6)] gives [1, 4, 9, 16, 25]. A condition can filter: [n for n in range(20) if n % 3 == 0]. Comprehensions are readable for simple transformations, but complicated logic is clearer as a normal loop.

Tuples and sets

A tuple is like a list but immutable: point = (3, 4). Tuples suit fixed groups of values, such as coordinates, and can be unpacked: x, y = point. A set is an unordered collection of unique items: set([1, 2, 2, 3]) is {1, 2, 3}. Sets support fast membership tests and operations such as union and intersection.

Dictionaries

A dictionary maps keys to values: ages = {"Ana": 15, "Ben": 16}. ages["Ana"] gives 15; assigning ages["Cara"] = 14 adds an entry. Looking up a missing key raises KeyError, so ages.get("Dan", 0) is safer, returning a default. Loop with for name, age in ages.items(). Keys must be immutable, such as strings, numbers, or tuples.

Choosing a collection

Use a list for an ordered sequence you will change; a tuple for a fixed record; a set for unique items and fast 'is it in there?' checks; and a dictionary to look things up by key. Checking membership in a set or dictionary is very fast on average, whereas checking a list means scanning it.

Worked example

Counting words: text = "the cat and the hat"; counts = {}; for word in text.split(): counts[word] = counts.get(word, 0) + 1. Result: {"the": 2, "cat": 1, "and": 1, "hat": 1}. The standard library's collections.Counter does the same in one line: Counter(text.split()). Its most_common(1) gives [("the", 2)].

Key takeaways

Lists are ordered and mutable, indexed from 0, with negative indexes from the end. append, insert, remove, pop, and sort modify lists; sorted() returns a new one. Slicing uses [start:stop:step]; [::-1] reverses. List comprehensions build lists concisely. Tuples are immutable and unpackable; sets hold unique items. Dictionaries map keys to values; use get() for safe lookup. Choose the collection that fits the job.

Flashcard

List

Ordered, mutable collection

[1, 2, 3].

Check your understanding

If nums = [10, 20, 30, 40, 50], what is nums[1:4]?

← Previous lesson Next lesson →