Quick reference
| Operation | Purpose |
|---|---|
| sort(), sorted() | Order elements |
| [::-1], reverse() | Reverse order |
| [:], copy(), list(), deepcopy() | Dulpicate data |
| index() | Locate first occurrence |
| len() | Count elements |
| count() | Frequency of value |
| str.join() | Concatenate to string |
| in / not in | Membership test |
| ==, !=, <, > | Lexicographic comparison |
| * | Replicate sequence |
Ordering elements: sort() vs. sorted()
Both functions accept key and reverse parameters. reverse=True flips the order; key lets you pick a criterion (e.g., a field in nested data).
In-place ordering with sort()
nums = [0, 3, 2, 1, 4, 9, 6, 8, 7, 5]
nums.sort()
print(nums) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nums.sort(reverse=True)
print(nums) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Non-destructive ordering with sorted()
src = [0, 3, 2, 1, 4, 9, 6, 8, 7, 5]
asc = sorted(src)
desc = sorted(src, reverse=True)
print(src) # original untouched
print(asc) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(desc) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Custom key example
matrix = [[1, 2, 3], [9, 8, 7], [2, 4, 6], [3, 1, 9]]
by_first = sorted(matrix) # default: first element
by_second = sorted(matrix, key=lambda r: r[1]) # sort by second column
print(by_first) # [[1, 2, 3], [2, 4, 6], [3, 1, 9], [9, 8, 7]]
print(by_second) # [[3, 1, 9], [1, 2, 3], [2, 4, 6], [9, 8, 7]]
Reversing a list
Slice trick (creates a new list)
seq = [0, 1, 2, 3, 4, 5]
rev = seq[::-1]
print(seq) # [0, 1, 2, 3, 4, 5]
print(rev) # [5, 4, 3, 2, 1, 0]
reverse() method (in-place)
seq = [0, 1, 2, 3, 4, 5]
seq.reverse()
print(seq) # [5, 4, 3, 2, 1, 0]
Copying lists safely
Shallow copies
src = [0, 1, 2, 3, 4, 5]
c1 = src[:] # slice
c2 = src.copy() # built-in method
c3 = list(src) # constructor
print(c1, c2, c3) # all equal to src
Deep copy for nested structures
import copy
nested = [0, 1, 2, 3, 4, [100, 200]]
shallow = nested[:] # shares inner list
deep = copy.deepcopy(nested) # fully independent
nested[-1][0] = 999
print(nested) # [0, 1, 2, 3, 4, [999, 200]]
print(shallow) # [0, 1, 2, 3, 4, [999, 200]]
print(deep) # [0, 1, 2, 3, 4, [100, 200]]
Loctaing and counting elements
words = ['apple', 'banana', 'banana', 'orange']
print(words.index('banana')) # 1 (first match)
print(words.count('banana')) # 2
print(len(words)) # 4
String concatenation with join()
lines = ['hello world', 'I am oxxo', 'how are you?']
result = ', '.join(lines)
print(result) # hello world, I am oxxo, how are you?
Membership tests
words = ['apple', 'banana', 'orange']
print('orange' in words) # True
print('melon' in words) # False
print('grape' not in words) # True
Comparing lists
a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5]
print(a == b) # False
print(a != b) # True
print(a < b) # True (shorter list is smaller)
print(a >= b) # False
Repeating elements with *
base = ['apple', 'banana']
triple = base * 3
print(triple) # ['apple', 'banana', 'apple', 'banana', 'apple', 'banana']