Python Lists, Tuples, Sets and Dictionaries: When to Use Each
A practical guide to Python's built-in collections: lists, tuples, sets and dictionaries. Learn their methods, time complexity, comprehensions, the collections module and how to choose the right one.
Python has four built-in collection types that you'll use in almost every program: lists, tuples, sets and dictionaries. Picking the right one makes your code faster, safer and easier to read. This guide covers how each one works and when to reach for it.
The four collections at a glance#
| List | Tuple | Set | Dict | |
|---|---|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {"a": 1} |
| Ordered | Yes | Yes | No | Yes (insertion order, 3.7+) |
| Mutable | Yes | No | Yes | Yes |
| Duplicates | Allowed | Allowed | No | Keys unique |
| Lookup by | Index | Index | Membership | Key |
x in c | O(n) | O(n) | O(1) | O(1) for keys |
Lists: ordered, changeable sequences#
scores = [72, 88, 95]
scores.append(60) # [72, 88, 95, 60]
scores.insert(0, 100) # [100, 72, 88, 95, 60]
scores.extend([55, 81]) # add many
scores.remove(72) # remove first matching value
last = scores.pop() # remove and return the last item
scores.sort() # sort in place
top3 = sorted(scores, reverse=True)[:3] # new sorted list
print(scores[0], scores[-1]) # first and last
print(scores[1:4]) # slice
print(len(scores), sum(scores), max(scores))| Operation | Time |
|---|---|
lst[i], append, pop() | O(1) |
insert(0, x), pop(0), remove(x), x in lst | O(n) |
sort() | O(n log n) |
list.pop(0) shifts every element. For queues, use collections.deque, which adds and removes from both ends in O(1).
List comprehensions#
squares = [n * n for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]
names = [s.strip().title() for s in [" asha", "RAVI "]] # ['Asha', 'Ravi']
matrix = [[r * c for c in range(3)] for r in range(3)]The copy trap#
a = [1, 2, 3]
b = a # b points to the SAME list
b.append(4)
print(a) # [1, 2, 3, 4] ← surprise!
c = a.copy() # or list(a) or a[:] for a shallow copy
grid = [[0] * 3 for _ in range(3)] # correct 2D list
bad = [[0] * 3] * 3 # 3 references to ONE rowTuples: fixed records#
Tuples are like lists that can't change. Use them for fixed groups of values, like coordinates or database rows.
point = (3, 4)
rgb = (255, 128, 0)
single = (42,) # the comma makes it a tuple
x, y = point # unpacking
a, b = b, a # swap two variables with a tuple
def min_max(nums):
return min(nums), max(nums) # returns a tuple
low, high = min_max([4, 9, 1])Because they're immutable, tuples can be dictionary keys and set members, and they're slightly faster and lighter than lists.
from typing import NamedTuple
class Student(NamedTuple):
name: str
marks: int
s = Student("Asha", 91)
print(s.name, s.marks) # readable fields, still a tupleSets: unique items and fast membership#
tags = {"python", "dsa", "python"} # {'python', 'dsa'}: duplicates removed
tags.add("web")
tags.discard("java") # no error if missing
print("dsa" in tags) # O(1) lookup
emails = ["a@x.com", "b@x.com", "a@x.com"]
unique = list(set(emails)) # remove duplicates (order not kept)
unique_ordered = list(dict.fromkeys(emails)) # remove duplicates, keep order
empty = set() # NOT {} (that's an empty dict)Set operations#
python_devs = {"Asha", "Ravi", "Meera"}
java_devs = {"Ravi", "Karan"}
print(python_devs | java_devs) # union: everyone
print(python_devs & java_devs) # intersection: {'Ravi'}
print(python_devs - java_devs) # difference: {'Asha', 'Meera'}
print(python_devs ^ java_devs) # symmetric differenceDictionaries: key-value lookups#
user = {"name": "Asha", "age": 21, "skills": ["python", "sql"]}
print(user["name"]) # KeyError if missing
print(user.get("email", "n/a")) # safe access with a default
user["email"] = "asha@example.com" # add or update
user.update({"age": 22, "city": "Pune"})
del user["city"]
for key, value in user.items():
print(key, value)
print(list(user.keys()), list(user.values()))Dict comprehensions and counting#
prices = {"apple": 120, "mango": 80, "kiwi": 150}
discounted = {k: v * 0.9 for k, v in prices.items() if v > 100}
text = "the quick brown fox jumps over the lazy dog the end"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts["the"]) # 3Dictionary keys and set members must be hashable: strings, numbers, tuples of hashables. Lists and dicts can't be keys because they can change.
The collections module#
from collections import Counter, defaultdict, deque, OrderedDict
# Counter: counting made easy
words = text.split()
print(Counter(words).most_common(2)) # [('the', 3), ('quick', 1)]
# defaultdict: no KeyError for new keys
groups = defaultdict(list)
for name, dept in [("Asha", "eng"), ("Ravi", "eng"), ("Meera", "hr")]:
groups[dept].append(name)
# {'eng': ['Asha', 'Ravi'], 'hr': ['Meera']}
# deque: fast queue and sliding windows
q = deque([1, 2, 3])
q.appendleft(0)
q.popleft()
recent = deque(maxlen=3) # keeps only the last 3 itemsdeque and dictionaries are the building blocks of many DSA techniques; see the sliding window technique.
How to choose#
| You need to… | Use |
|---|---|
| Keep items in order and change them | List |
| Store a fixed record or return several values | Tuple |
| Remove duplicates or check membership fast | Set |
| Look things up by name or ID | Dict |
| Count occurrences | Counter |
| Group items by a key | defaultdict(list) |
| Add/remove at both ends | deque |
# Real-world speed difference
banned = ["spam", "scam", "fake", ...] # list: each check is O(n)
banned = {"spam", "scam", "fake", ...} # set: each check is O(1)
clean = [w for w in words if w not in banned]Understanding why these operations are O(1) or O(n) is covered in Big O notation explained. Java developers can compare with the Java Collections Framework.
Key takeaways#
- Lists are ordered and mutable; tuples are ordered and immutable.
- Sets store unique items with O(1) membership checks; dicts map unique keys to values with O(1) lookup.
- Comprehensions build lists, sets and dicts in one readable line.
- Beware of aliasing: assigning a list doesn't copy it.
- Use
Counter,defaultdictanddequefromcollectionsfor counting, grouping and queues.