Skip to Content

Lists, Tuples, Sets & Dicts

When to use

Group values and pick the right container by order, uniqueness, key access.

Analogy

List is a row of cubbies; tuple is the same but you’ve lost the keys; set is a bag (no duplicates); dict is a labelled filing cabinet.

Data-flow diagram

list   [1,2,3]   ordered, mutable,  dup OK
tuple  (1,2,3)   ordered, immutable, hashable
set    {1,2,3}   unordered, unique, O(1) `in`
dict   {'a':1}   insertion-ordered since 3.7

Deep explanation

List is your default for ordered mutable sequences. Tuple is the immutable hashable record. Set is for O(1) membership and de-duplication. Dict is the workhorse hashmap (O(1) key lookup). Pick by what you need: don’t list-membership a million items.

Examples

Example 1

fruits = ['apple','banana','apple']
print(len(fruits), fruits.count('apple'))

list keeps duplicates and order; useful for logs.

Example 2

unique = set(fruits)
'apple' in unique   # O(1)

set is O(1) for in; great for de-duplication.

Example 3

point = (3, 4)
{'x': point[0], 'y': point[1]}

Tuple is hashable, so it can be a dict key (lists cannot).

Common mistake

x in some_list over millions of items in a hot loop - O(n). Use a set or dict (O(1)). Also: tuple records containing mutable lists are ‘immutable’ only at the surface - the list inside can still change.

Key takeaway

dict for kv; list for ordered mutation; tuple for fixed records; set for in-checks and dedup. Never use a list as a lookup table on >1000 items.

Production Failure Playbook

Failure scenario 1: list-as-lookup-at-1m

Failure scenario 2: dict-mutated-during-iter