π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.
Β§ 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
Checkpoint quiz
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.