Module 6: Lists -- Quick Reference
A printable reference card covering list creation, methods, slicing, and comprehensions.
Creating Lists
| Syntax | Description | Example |
|---|---|---|
[] | Empty list | items = [] |
[a, b, c] | List with values | nums = [1, 2, 3] |
list() | Empty list (constructor) | items = list() |
list(iterable) | Convert to list | list("abc") → ["a","b","c"] |
list(range(n)) | List from range | list(range(5)) → [0,1,2,3,4] |
Accessing Elements
| Syntax | Description | Example (lst = [10,20,30,40,50]) |
|---|---|---|
lst[0] | First element | 10 |
lst[-1] | Last element | 50 |
lst[-2] | Second to last | 40 |
len(lst) | Number of items | 5 |
x in lst | Membership check | 30 in lst → True |
x not in lst | Not in check | 99 not in lst → True |
List Methods
| Method | Description | Returns |
|---|---|---|
lst.append(x) | Add x to the end | None |
lst.insert(i, x) | Insert x at index i | None |
lst.extend(iter) | Add all items from iterable | None |
lst.remove(x) | Remove first occurrence of x | None |
lst.pop() | Remove and return last item | The item |
lst.pop(i) | Remove and return item at i | The item |
lst.clear() | Remove all items | None |
lst.sort() | Sort ascending in place | None |
lst.sort(reverse=True) | Sort descending in place | None |
lst.reverse() | Reverse order in place | None |
lst.count(x) | Count occurrences of x | Integer |
lst.index(x) | Index of first x | Integer |
lst.copy() | Shallow copy | New list |
Slicing
| Syntax | Description | Example (lst = [0,1,2,3,4,5,6,7,8,9]) |
|---|---|---|
lst[a:b] | From index a to b-1 | lst[2:5] → [2,3,4] |
lst[:b] | From start to b-1 | lst[:3] → [0,1,2] |
lst[a:] | From a to end | lst[7:] → [7,8,9] |
lst[:] | Copy entire list | lst[:] → [0,1,...,9] |
lst[::n] | Every nth element | lst[::2] → [0,2,4,6,8] |
lst[::-1] | Reversed copy | lst[::-1] → [9,8,...,0] |
lst[-3:] | Last 3 elements | lst[-3:] → [7,8,9] |
List Comprehensions
| Pattern | Syntax | Example |
|---|---|---|
| Basic | [expr for x in iter] | [x**2 for x in range(5)] |
| With filter | [expr for x in iter if cond] | [x for x in nums if x > 0] |
| With if/else | [A if cond else B for x in iter] | ["even" if x%2==0 else "odd" for x in nums] |
Built-in Functions for Lists
| Function | Description | Example |
|---|---|---|
len(lst) | Number of items | len([1,2,3]) → 3 |
sum(lst) | Sum of items | sum([1,2,3]) → 6 |
min(lst) | Smallest item | min([3,1,2]) → 1 |
max(lst) | Largest item | max([3,1,2]) → 3 |
sorted(lst) | New sorted list | sorted([3,1,2]) → [1,2,3] |
reversed(lst) | Reverse iterator | list(reversed([1,2,3])) → [3,2,1] |