L3Β·Functions & Modules

πŸ“šMaster Reference: 68 Built-in Functions & Core Data Structure Methods

Exhaustive cheat sheet of Python built-in functions, string methods, list methods, dict methods, and set methods with syntax, edge cases, and time complexities.

built-insstr methodslist methodsdict methodsset methodsreference

Β§ 1Essential built-in functions

Python ships 68 built-ins that need no import. These are the ones asked most in coding rounds. Format: signature β†’ return type β€” example.

1len(obj) β†’ int len([1,2,3]) == 3 # O(1)​
2range(start, stop, step) β†’ range list(range(0,6,2)) == [0,2,4] # lazy​
3enumerate(it, start=0) β†’ iterator list(enumerate('ab')) == [(0,'a'),(1,'b')]​
4zip(*its) β†’ iterator list(zip([1,2],'ab')) == [(1,'a'),(2,'b')] # stops at shortest​
5map(fn, it) β†’ iterator list(map(str,[1,2])) == ['1','2']​
6filter(fn, it) β†’ iterator list(filter(None,[0,1,''])) == [1]​
7sorted(it, key, reverse) β†’ list sorted('cab') == ['a','b','c'] # O(n log n), new list​
8reversed(seq) β†’ iterator list(reversed([1,2])) == [2,1]​
9any(it) / all(it) β†’ bool any([]) == False; all([]) == True​
10sum(it, start=0) β†’ number sum([1,2,3]) == 6​
11min(it, key) / max β†’ item max(['aa','b'], key=len) == 'aa'​
12abs(x) β†’ number abs(-3.5) == 3.5​
13round(x, nd) β†’ int/float round(2.5) == 2 # banker's rounding​
14isinstance(obj, cls) β†’ bool isinstance(True, int) == True​
15type(obj) β†’ type type([]) is list​
16id(obj) β†’ int identity (memory address in CPython)​
17hash(obj) β†’ int hash([1]) β†’ TypeError (unhashable)​
18dir(obj) β†’ list names of attributes​
19getattr(obj, name, dflt) β†’ value getattr(obj, 'x', 0)​
20hasattr(obj, name) β†’ bool hasattr('', 'upper') == True​
21open(path, mode) β†’ file with open('a.txt') as f: ...​

Β§ 2String methods

Strings are immutable, so every method returns a new string (or bool/int/list). Most are O(n).

1' hi '.strip() β†’ 'hi' # also lstrip/rstrip, strip('xy')​
2'a,b,,c'.split(',') β†’ ['a','b','','c']​
3'a b'.split() β†’ ['a','b'] # no arg: splits on any whitespace​
4'-'.join(['a','b']) β†’ 'a-b' # items must be str​
5'aaa'.replace('a','b',2) β†’ 'bba'​
6'hello'.find('l') β†’ 2 (-1 if missing; .index raises ValueError)​
7'banana'.count('an') β†’ 2 # non-overlapping​
8'file.py'.startswith(('a','f')) β†’ True # accepts a tuple​
9'file.py'.endswith('.py') β†’ True​
10'PyThOn'.lower() / .upper() β†’ 'python' / 'PYTHON'​
11"it's me".title() β†’ "It'S Me" # edge case!​
12'42'.isdigit() β†’ True ; '-4'.isdigit() β†’ False​
13'abc'.isalpha() β†’ True ; ''.isalpha() β†’ False​
14'7'.zfill(3) β†’ '007' ; '-7'.zfill(3) β†’ '-07'​

Β§ 3List methods

Lists are mutable; these methods change the list in place and most return None. append/pop() are O(1); insert/remove/pop(0)/index are O(n); sort is O(n log n).

1a = [3, 1, 2]​
2a.append(4) # [3,1,2,4] returns None​
3a.extend([5, 6]) # adds each item (append([5,6]) would nest a list)​
4a.insert(0, 9) # [9,3,1,2,4,5,6]​
5a.remove(9) # first matching value; ValueError if absent​
6a.pop() # β†’ 6 (last); a.pop(0) β†’ 3 (O(n))​
7a.index(2) # β†’ position; ValueError if absent​
8a.count(1) # β†’ 1​
9a.sort(key=lambda x: -x) # in place, returns None, stable​
10a.reverse() # in place​
11b = a.copy() # shallow copy (same as a[:])​
12a.clear() # []​

Β§ 4Dictionary methods

Dicts keep insertion order (3.7+). get/set/delete are O(1) on average. keys/values/items return live views.

1d = {'a': 1, 'b': 2}​
2d.keys() # dict_keys(['a','b'])​
3d.values() # dict_values([1,2])​
4d.items() # dict_items([('a',1),('b',2)])​
5d.get('z') # None (no KeyError)​
6d.get('z', 0) # 0 β€” d['z'] would raise KeyError​
7d.pop('a') # β†’ 1 ; d.pop('z', None) avoids KeyError​
8d.update({'c': 3}) # merge (also d | other in 3.9+)​
9d.setdefault('L', []).append(1) # insert default only if missing​
10d.popitem() # removes & returns LAST inserted pair (LIFO)​

Β§ 5Set methods

Sets hold unique, hashable items with O(1) average add/remove/membership. Methods accept any iterable; operators need sets on both sides.

1s = {1, 2, 3}​
2s.add(4) # {1,2,3,4}​
3s.discard(10) # no error if missing​
4s.remove(10) # KeyError if missing​
5s.union([5]) # {1,2,3,4,5} same as s | {5}​
6s.intersection({2, 9}) # {2} s & {2,9}​
7s.difference({1}) # {2,3,4} s - {1}​
8s.symmetric_difference({4,7}) # {1,2,3,7} s ^ {4,7}​
9{1,2}.issubset(s) # True {1,2} <= s​
10s.issuperset({1}) # True s >= {1}​
11s - [1] # TypeError β€” operator needs a set; method accepts a list​

Worked example

1words = ["spark", "sql", "java", "sql", "python"]​
2​
3freq = {}​
4for w in words:​
5 freq[w] = freq.get(w, 0) + 1​
6print(freq)​
7​
8unique_sorted = sorted(set(words), key=len)​
9print(unique_sorted)​
10​
11for i, (w, n) in enumerate(zip(words, map(len, words)), start=1):​
12 print(i, w.title().zfill(8), n)​
13​
14print(any(w.startswith("py") for w in words), all(words))​
15print(set(words) - {"sql"})​

Try it live Β· Python runs in your browser

Loading playground…
ChallengeGiven a sentence, print the 3 most common words (case-insensitive, ignoring punctuation) using only built-ins and str/dict methods.

Checkpoint quiz

Question 1 / 5
nums = [3, 1, 2]; x = nums.sort(). What is x?

Lesson test

Take an 8-question test on β€œMaster Reference: 68 Built-in Functions & Core Data Structure Methods” β€” concepts, output prediction, bug spotting and interview questions.