Essential Python Functions, Data Structures & Algorithms
Counts how many times each element appears.
Counter([1, 2, 2, 3])
Returns: {1: 1, 2: 2, 3: 1}
Used to loop through both keys and values.
Counter('aab').items()
Returns: [('a', 2), ('b', 1)]
Extracts only the counts or values.
Counter('aab').values()
Returns: [2, 1]
Used with Counter to get most frequent elements.
Counter('aab').most_common(1)
Returns: [('a', 2)]
Unordered collection of unique elements.
set([1, 2, 2, 3])
Returns: {1, 2, 3}
s.add(4)
Adds element 4
s.remove(2)
Removes element 2
s1.union(s2)
Combines two sets
Key-value pairs for fast lookups.
d = {1: "a", 2: "b"}
Creates dictionary
d.get(1, "default")
Returns "a" or "default" if key missing
d.keys()
Returns: dict_keys([1, 2])
d.setdefault(3, "c")
Sets default if key doesn't exist
Essential list methods for dynamic arrays.
nums.append(5)
Adds 5 to end
nums.pop()
Removes and returns last element
nums.insert(0, 1)
Inserts 1 at index 0
nums[1:4]
Slicing: elements 1 to 3
Combines multiple lists into tuples.
zip([1, 2], ['a', 'b'])
Returns: [(1, 'a'), (2, 'b')]
Gives (index, value) when looping through a list.
enumerate(['x', 'y'])
Returns: [(0, 'x'), (1, 'y')]
Sorts list in place. Reorders the list without creating a new one.
nums = [3, 1, 2]; nums.sort()
Returns: [1, 2, 3] (in-place)
nums.sort(reverse=True)
Returns: [3, 2, 1] (in-place)
Returns the smallest item from an iterable or the smallest of two or more arguments.
min([3, 1, 4, 2])
Returns: 1
min(10, 20)
Returns: 10
Returns the largest item from an iterable or the largest of two or more arguments.
max([3, 1, 4, 2])
Returns: 4
max(10, 20)
Returns: 20
Joins elements of an iterable into a single string, with a separator.
' '.join(['Hello', 'world'])
Returns: 'Hello world'
'-'.join(['1', '2', '3'])
Returns: '1-2-3'
Splits a string into a list based on a separator.
'Hello world'.split()
Returns: ['Hello', 'world']
'apple,banana,orange'.split(',')
Returns: ['apple', 'banana', 'orange']
Applies a function cumulatively to the items of an iterable, reducing it to a single value.
reduce(operator.xor, [1, 2, 3])
Returns: 0
Efficient for queue operations from both ends.
from collections import deque
Import statement
d = deque([1, 2, 3])
Creates deque
d.appendleft(0)
Adds to left end
d.popleft()
Removes from left end
Applies a function to each item of an iterable.
map(lambda x: x*2, [1, 2, 3])
Returns: [2, 4, 6]
list(map(str, [1, 2, 3]))
Returns: ['1', '2', '3']
Filters items based on a condition.
filter(lambda x: x > 2, [1, 2, 3, 4])
Returns: [3, 4]
list(filter(None, [0, 1, False, True]))
Returns: [1, True]
Short anonymous function.
f = lambda x: x**2
Creates square function
f(2)
lambda x, y: x + y
Anonymous addition function
Concise iteration and transformation.
[x for x in range(5)]
Returns: [0, 1, 2, 3, 4]
[x*2 for x in [1,2,3] if x > 1]
Returns: [4, 6]
[[i,j] for i in range(2) for j in range(2)]
Returns: [[0,0], [0,1], [1,0], [1,1]]
Efficient searching in sorted lists.
import bisect
bisect.bisect_left([1, 2, 4, 5], 3)
Returns: 2 (insertion point)
bisect.bisect_right([1, 2, 2, 3], 2)
Returns: 3 (rightmost insertion)
Used for sorted arrays or linked lists.
left, right = 0, len(nums) - 1
Initialize pointers
while left < right:
Two pointer loop pattern
# Move pointers based on condition
Common pattern for array problems
For subarray/substring problems.
left = right = 0
Initialize window
while right < len(s):
Expand window
while condition: left += 1
Shrink window
Recursive tree/graph traversal.
def dfs(node):
Base case: if not node
# Process current node
Recursive calls
dfs(node.left)
dfs(node.right)
Level-wise tree/graph traversal.
Import for queue
queue = deque([root])
Initialize queue
while queue:
Process level by level
node = queue.popleft()
Process current node
For tracking connected components.
parent = list(range(n))
Initialize parents
def find(x):
Find root with path compression
def union(x, y):
Union by rank/size
Common mathematical functions.
import math
math.sqrt(16)
Returns: 4.0
math.ceil(3.2)
math.gcd(12, 18)
Returns: 6
Prevents overflow and cyclic operations.
17 % 5
Returns: 2
(-3) % 5
Returns: 2 (Python behavior)
for i in range(10): i % 3
Cyclic: 0, 1, 2, 0, 1, 2...
Efficient power operations.
2 ** 3
Returns: 8
pow(2, 3, 5)
Returns: 3 (2^3 % 5)
pow(2, -1, 7)
Returns: 4 (modular inverse)