·2 min read
Python for DSA — Built-in Functions & Modules
PythonDsaBuiltinsModulesCollectionsHeapq
8. Built-in Functions & Modules
💡 Why this matters for DSA Python's built-in functions are optimized C implementations — faster than writing loops yourself. Using them is both cleaner and faster.
8.1 Core Built-ins
python
arr = [3, 1, 7, 2, 7, 5]
len(arr) # 6
sum(arr) # 25
min(arr) # 1
max(arr) # 7
sorted(arr) # [1, 2, 3, 5, 7, 7] (new list)
sorted(arr, reverse=True) # [7, 7, 5, 3, 2, 1]
reversed(arr) # returns iterator; use list(reversed(arr))
✅ Tip —
sum()with generator — compact & efficient:pythontotal = sum(x**2 for x in arr) # sum of squares count = sum(1 for x in arr if x > 0) # count positives
8.2 map() & filter()
map — apply a function to every element
python
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums)) # [1, 4, 9, 16]
strings = list(map(str, nums)) # ["1", "2", "3", "4"]
filter — keep elements that satisfy a condition
python
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
🔑 Key — map/filter vs comprehension:
python# ✅ Prefer comprehensions — more Pythonic squared = [x**2 for x in nums] evens = [x for x in nums if x % 2 == 0] # map/filter is useful when you already have a named function strings = list(map(str, nums)) nums_again = list(map(int, strings))
8.3 zip() & enumerate()
Covered in detail in the Loops post. Quick recap:
python
zip([1,2,3], ['a','b','c']) # (1,'a'), (2,'b'), (3,'c')
enumerate(['a','b','c']) # (0,'a'), (1,'b'), (2,'c')
8.4 abs(), ord(), chr()
python
abs(-5) # 5
abs(3 - 7) # 4 (distance)
ord('a') # 97 (char → ASCII)
chr(97) # 'a' (ASCII → char)
ord('0') # 48
# Common DSA pattern: char to index
pos = ord('z') - ord('a') # 25
✅ Tip —
abs()for distance calculations:python# Manhattan distance dist = abs(x1 - x2) + abs(y1 - y2)
8.5 Importing
python
# Import specific functions
from math import sqrt, floor
sqrt(16) # 4.0
# Import module (use module.function)
import math
math.floor(3.7) # 3
# Import with alias
from collections import defaultdict, Counter, deque
import heapq as hq
✅ Tip — What to import for DSA: Import only what you need — it's cleaner and avoids namespace pollution.
python# Your DSA import toolkit: from collections import defaultdict, Counter, deque import heapq import sys sys.setrecursionlimit(10**6)
8.6 Common Built-in Patterns for DSA
python
# Remove duplicates (order NOT preserved)
unique = list(set(arr))
# Check if all elements satisfy condition
all(x > 0 for x in arr) # True if ALL positive
any(x < 0 for x in arr) # True if ANY negative
# Flatten a list of lists
flat = [x for sublist in matrix for x in sublist]
# Transpose a matrix (zip trick)
transposed = list(zip(*matrix))
# Most frequent element
from collections import Counter
most_common = Counter(arr).most_common(1)[0][0]
# Custom sort with multiple keys
sorted(arr, key=lambda x: (x["score"], -x["age"]))
Practice Drill
python
# 1. Sort words by their length (shortest first)
# 2. Convert ["1", "2", "3"] to [1, 2, 3] in one line
# 3. Check if all elements in a list are even
# 4. Find the sum of squares of odd numbers only
💡 Click for Solutions
python
# 1. Sort by length
words = ["python", "go", "java", "rust"]
print(sorted(words, key=len)) # ['go', 'rust', 'java', 'python']
# 2. String list to int list
s = ["1", "2", "3"]
nums = list(map(int, s)) # [1, 2, 3]
# 3. All even?
arr = [2, 4, 6, 8]
print(all(x % 2 == 0 for x in arr)) # True
# 4. Sum of squares of odds
arr = [1, 2, 3, 4, 5]
result = sum(x**2 for x in arr if x % 2 != 0)
print(result) # 1 + 9 + 25 = 35
← Functions & Recursion | Next → List & Dict Utilities