Source: Python Ultimate Cheat Sheet / Python 3 Cheat Sheet / Python for Data Science Cheat Sheet
Difficulty: Beginner to Intermediate | Prerequisites: Python 3 Fundamentals (data types, variables, operators).
Once you can store single values in variables, the next step is organising collections of values. Python provides four built-in container types, each with different trade-offs around ordering, mutability and key access. Lists and tuples handle ordered sequences, dictionaries handle key-value lookups, and sets handle unique membership. Nearly every Python program beyond "Hello World" uses at least one of these, so fluency with their syntax and methods is essential before you move on to control flow and functions.
Lists are mutable ordered sequences (square brackets). Tuples are immutable ordered sequences (parentheses). Dictionaries map unique keys to values (curly braces with colons). Sets store unique unordered items (curly braces, no colons). Know how to index, slice, add, remove and iterate over each one.
list
A mutable, ordered sequence of items, written with square brackets: [1, 2, 3].
Think of it as a numbered row of boxes you can add to, remove from, and rearrange.
tuple
An immutable, ordered sequence of items, written with parentheses: (1, 2, 3).
In simple terms, this means a list you cannot change after creation. Tuples are slightly faster and can serve as dictionary keys.
dict (dictionary)
A mutable, unordered collection of key-value pairs, written with curly braces: {"name": "Alice", "age": 30}.
Think of it as a lookup table where you find a value by its key instead of by position.
set
A mutable, unordered collection of unique items, written with curly braces: {1, 9, 3, 0}.
In simple terms, a set is a bag of distinct values. Duplicates are automatically removed. An empty set is set(), not {} (that creates an empty dict).
frozenset
An immutable version of a set. Can be used as a dictionary key or as a member of another set.
Index
The position of an item in an ordered sequence. Python uses zero-based indexing: the first item is at index 0.
Slice
A sub-sequence extracted with the syntax sequence[start:end:step]. The start is inclusive, the end is exclusive.
Mutable
An object whose contents can be changed after creation. Lists, dicts and sets are mutable.
Immutable
An object whose contents cannot be changed after creation. Tuples, strings, frozensets and bytes are immutable.
Hashable
An object that has a fixed hash value for its lifetime. Only hashable objects can serve as dict keys or set members. All immutable base types are hashable.
For any ordered sequence lst = [10, 20, 30, 40, 50]:
Positive indices run 0, 1, 2, 3, 4. Negative indices run -5, -4, -3, -2, -1.
lst[0] returns 10 (first). lst[-1] returns 50 (last). lst[1] returns 20. lst[-2] returns 40.
len(lst) returns 5.
Slicing with lst[start:end:step]:
lst[1:3] returns [20, 30] (indices 1 and 2, end is exclusive).
lst[:3] returns [10, 20, 30] (from start up to but not including index 3).
lst[3:] returns [40, 50] (from index 3 to end).
lst[:-1] returns [10, 20, 30, 40] (everything except the last item).
lst[::2] returns [10, 30, 50] (every second item).
lst[::-1] returns [50, 40, 30, 20, 10] (reversed copy).
lst[:] returns a shallow copy of the entire list.
On mutable sequences, you can delete with del lst[3] or del lst[3:5], and modify with assignment: lst[4] = 25 or lst[1:4] = [15, 25].
Create: my_list = [1, 2, 3] or list(("a", "b", "c")).
Key methods:
lst.append(val) adds one item to the end.
lst.extend(seq) adds all items from another sequence to the end.
lst.insert(idx, val) inserts at a specific index.
lst.remove(val) removes the first occurrence of a value.
lst.pop([idx]) removes and returns an item at the given index (default: last).
lst.sort() sorts in place. lst.reverse() reverses in place.
lst.index(val) returns the index of the first occurrence.
lst.count(val) counts how many times a value appears.
lst.copy() returns a shallow copy.
Combining: list_a + list_b concatenates. lst * 3 replicates.
Nested lists: my_list2 = [[4, 5, 6], [7, 8, 9]]. Access inner items with my_list2[1][0] which returns 7.
List comprehensions: [x ** 2 for x in range(10) if x % 2 == 0] returns [0, 4, 16, 36, 64]. This is a compact way to build lists by applying an expression and an optional filter to each item in an iterable.
Create: my_tuple = (1, 2, 3, 4, 5) or simply 1, 2, 3 (the comma makes the tuple, not the parentheses).
A single-item tuple needs a trailing comma: ("mot",) not ("mot").
Tuples support indexing and slicing just like lists. my_tuple[0:3] returns (1, 2, 3).
Tuples are immutable: you cannot append, remove or reassign items. To "change" a tuple, convert to a list, modify, and convert back:
x = ("apple", "orange", "pear")
y = list(x)
y[1] = "grape"
x = tuple(y)Tuples are slightly faster than lists and can be used as dictionary keys (because they are hashable, provided all their elements are also hashable).
Create: new_dict = {"brand": "Honda", "model": "Civic", "year": 1995} or dict(a=3, b=4, k="v").
Access: new_dict["brand"] returns "Honda". Use d.get(key, default) to avoid a KeyError if the key might be missing.
Modify: new_dict["year"] = 2020 changes an existing key or adds a new one.
Key methods:
d.keys() returns a view of all keys.
d.values() returns a view of all values.
d.items() returns a view of (key, value) tuples.
d.update(d2) merges another dictionary in.
d.pop(key[, default]) removes a key and returns its value.
d.clear() empties the dictionary.
del d[key] removes a single key-value pair.
Looping: for key in d: iterates over keys. for k, v in d.items(): iterates over both.
Dictionary keys must be hashable (typically strings, numbers, or tuples).
Create: {1, 9, 3, 0} or set(["one", "two"]). An empty set is set(), not {}.
Sets automatically discard duplicates. They are unordered, so you cannot index into them.
Operators:
| union, & intersection, - difference, ^ symmetric difference.
<, <=, >, >= test subset and superset relations.
Key methods: s.add(key), s.remove(key) (raises KeyError if missing), s.discard(key) (no error if missing), s.pop() (removes an arbitrary item), s.copy(), s.clear().
These work on lists, tuples, strings, bytes and (where applicable) dicts and sets:
len(c) returns the item count.
min(c), max(c), sum(c) for numeric sequences.
sorted(c) returns a new sorted list.
val in c tests membership (returns True or False). val not in c tests absence.
enumerate(c) yields (index, value) pairs.
zip(c1, c2) yields tuples of paired items.
all(c) returns True if every item is truthy. any(c) returns True if at least one is.
reversed(c) returns a reversed iterator (ordered sequences only).
c * 5 duplicates. c + c2 concatenates (ordered sequences only).
Lists are the workhorse for any ordered collection: reading lines from a file, storing database query results, or tracking items in a shopping cart. Dictionaries power configuration files, JSON data from web APIs, and any lookup-by-name scenario. Sets are the natural choice when you need to deduplicate data or perform membership checks on large collections efficiently.
Students often think {} creates an empty set. It does not. {} creates an empty dictionary. Use set() for an empty set.
Students often think tuples are just "lists you don't need to change." While that is one use, tuples also serve as hashable keys and as a way to return multiple values from a function. The immutability is a feature, not a limitation.
Students often think list slicing returns the item at the end index. It does not. lst[1:3] returns items at indices 1 and 2. The end index is always exclusive.
Students often confuse lst.append([4, 5]) with lst.extend([4, 5]). append adds the list as a single nested item. extend adds each element individually.
⚠️ Indexing and slicing are heavily tested. Be able to trace lst[1:-1], lst[::-1], and lst[::2] on a given list.
⚠️ Know the difference between mutable (list, dict, set) and immutable (tuple, frozenset, str) containers. Exam questions often ask which types can be dictionary keys.
⚠️ del, .remove(), and .pop() each work differently. Know when each raises an error and what it returns.
⚠️ Dictionary iteration: for k in d gives keys, not values. Use d.values() for values and d.items() for both.
True or False: lst = [10, 20, 30]; lst[-1] returns 10. (False, it returns 30, the last item.)
Fill in the blank: To create a single-element tuple, you write ______ after the value. (A trailing comma, e.g. (5,).)
True or False: {1, 2, 2, 3} produces {1, 2, 2, 3}. (False, it produces {1, 2, 3} because sets discard duplicates.)
Fill in the blank: d.get("missing_key", 0) returns ______ when the key does not exist. (0, the default value.)
True or False: lst[1:4] on [10, 20, 30, 40, 50] returns [20, 30, 40, 50]. (False, it returns [20, 30, 40] because the end index is exclusive.)
Q: Given fruits = ["apple", "banana", "orange"], write code to insert "grape" at index 1.
A: fruits.insert(1, "grape"). The list becomes ["apple", "grape", "banana", "orange"].
Q: What does my_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); print(my_tuple[1:11:2]) output?
A: (1, 3, 5, 7, 9). Start at index 1, stop before 11, step by 2.
Q: How do you remove the key "model" from a dictionary car = {"brand": "Honda", "model": "Civic"}?
A: del car["model"] or car.pop("model").
Q: Given a = {1, 2, 3} and b = {2, 3, 4}, what is a & b?
A: {2, 3}. The & operator returns the intersection (items in both sets).
Q: What is the difference between list.sort() and sorted(list)?
A: list.sort() sorts the list in place and returns None. sorted(list) returns a new sorted list, leaving the original unchanged.
This connects to Control Flow because for loops iterate over lists, tuples, dicts and sets, and if statements often test membership with in.
This connects to Functions because functions frequently accept lists or dicts as arguments and return tuples to pass back multiple values.
This connects to File I/O because reading a file typically produces a list of lines, and parsing structured data (JSON, CSV) produces dicts and lists.
Python list, Python tuple, Python dictionary, Python set, frozenset, indexing, slicing, zero-based index, negative index, mutable vs immutable, append extend insert remove pop, sort reverse, list comprehension, dict keys values items, set union intersection difference, hashable, shallow copy, nested list, sequence unpacking, enumerate zip, container types, Python 3 data structures