Python for DSA
Use Python's concise syntax and built-ins (list, dict, set, heapq, deque, bisect, Counter) to solve interview problems quickly, while knowing its performance limits.
Beginner · about 15 hours · difficulty 1/5
Python lets you express an algorithm in very few lines, which is great in interviews where clarity matters. The trade-off is speed: Python is often 10-50x slower than C++, so some contest problems with tight limits are hard to pass. For interviews and most online assessments it is perfectly fine.
What to actually learn
- Built-ins:
list(dynamic array),dict,set,tuple, slicing, list comprehensions,enumerate,zip,sorted(key=...). collections:deque(O(1) pops from both ends;list.pop(0)is O(n)),Counter,defaultdict.heapq: a min-heap on a plain list. For a max-heap, push negated values or tuples.bisect:bisect_left/bisect_rightfor binary search on sorted lists.functools.lru_cache(orcache) for quick memoization in DP.
Pitfalls
- Recursion limit defaults to about 1000; call
sys.setrecursionlimitor convert deep DFS to iterative. [[0] * m] * ncreates n references to the same row. Use[[0] * m for _ in range(n)].- Strings are immutable; build with a list and
"".join(parts). - Use
sys.stdin.readlinefor large input.
Good enough to move on: you can write BFS with deque, Dijkstra with heapq, and a memoized recursive DP, and you know which operations are O(1) versus O(n).
Key concepts
- Lists, slicing and comprehensions
- dict and set
- collections.deque
- Counter and defaultdict
- heapq (min-heap)
- bisect for binary search
- lru_cache for memoization
- Recursion limit and fast input
Other options for this step
- C++ for DSA: Learn the slice of modern C++ that matters for interviews and contests: fast I/O, references, the STL containers and algorithms, and common gotchas.
- Java for DSA: Use Java and its Collections Framework for DSA: ArrayList, HashMap, TreeMap, PriorityQueue, ArrayDeque, plus fast input and common boxing traps.
Mini project
Solve 6 warm-ups in Python: group anagrams with defaultdict, top-k frequent with Counter and heapq, BFS on a grid with deque, count elements in a range with bisect, memoized Fibonacci with lru_cache, and a max-heap of tasks using negated priorities.
Check yourself
What is wrong with grid = [[0] * 3] * 3, and why does using list.pop(0) inside a BFS loop hurt performance?
Free resources
- The Python Tutorial (Python.org)
- collections module (Python.org)
- heapq module (Python.org)