Ultimate Python Cheat Sheet for LeetCode & Data Structures

0.0(0)
studied byStudied by 1 person
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/76

flashcard set

Earn XP

Description and Tags

A comprehensive set of Q&A flashcards covering core list, string, dict, set, deque, heapq, collections, itertools, and math operations, bitwise tricks, recursion helpers, unpacking patterns, comprehensions, and Pythonic idioms from the Ultimate Python Cheat Sheet for LeetCode prep.

Last updated 10:20 PM on 7/23/25
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai

No analytics yet

Send a link to your students to track their progress

77 Terms

1
New cards

What does list.append(x) do?

Adds item x to the end of the list.

2
New cards

How does list.extend(iterable) modify a list?

Appends each element from the iterable to the end of the list.

3
New cards

What is the effect of list.insert(i, x)?

Inserts x at index i, shifting subsequent items right.

4
New cards

How does list.remove(x) work?

Removes the first occurrence of value x from the list.

5
New cards

What value does list.pop([i]) return?

Removes and returns the item at index i (last item if i is omitted).

6
New cards

What does list.reverse() do?

Reverses the elements of the list in place.

7
New cards

How does list.sort() affect a list?

Sorts the list in place in ascending order by default.

8
New cards

What is the purpose of list.copy()?

Returns a shallow copy of the list.

9
New cards

What does str.split(sep=None) return?

A list of substrings split on sep (whitespace if sep is None).

10
New cards

How is str.join(iterable) used?

Concatenates the strings in iterable, placing the original string as the separator.

11
New cards

What does str.strip() remove?

Leading and trailing whitespace (or specified characters).

12
New cards

How does str.replace(old, new) modify a string?

Returns a copy with all occurrences of old replaced by new.

13
New cards

What does str.find(sub) output?

Lowest index where substring sub is found, or -1 if absent.

14
New cards

What check does str.startswith(prefix) perform?

Returns True if the string begins with prefix.

15
New cards

What is returned by str.upper()?

An uppercase version of the string.

16
New cards

How does dict.get(key, default=None) behave?

Returns value for key if present, else default.

17
New cards

What does dict.items() provide?

A view of the dictionary’s key–value pairs.

18
New cards

How does dict.pop(key) work?

Removes key and returns its value; raises KeyError if key absent.

19
New cards

What is dict.popitem() used for?

Removes and returns the last inserted key–value pair (LIFO).

20
New cards

How does dict.update(other) modify a dictionary?

Merges key–value pairs from other, overwriting existing keys.

21
New cards

What does dict.setdefault(key, default) do?

Returns value if key exists; otherwise inserts key with default and returns default.

22
New cards

How does set.add(elem) modify a set?

Adds elem to the set if not already present.

23
New cards

What is the difference between set.remove(elem) and set.discard(elem)?

remove raises KeyError if elem absent; discard silently does nothing.

24
New cards

How is set.union(other) used?

Returns a new set containing elements from both sets.

25
New cards

What result does set.intersection(other) give?

A set of elements common to both sets.

26
New cards

What does set.difference(other) return?

Elements present in the first set but not in other.

27
New cards

What does set.issubset(other) test?

True if every element of the set is also in other.

28
New cards

What does len(obj) provide in Python?

The number of items in obj (for sequences, mappings, etc.).

29
New cards

How does sum(iterable) operate?

Returns the total of the items in the iterable (optionally plus a start value).

30
New cards

What does sorted(iterable) return?

A new list containing the items from iterable in ascending order.

31
New cards

Why is enumerate(iterable) useful?

Yields (index, value) pairs while iterating over iterable.

32
New cards

What does zip(*iterables) generate?

Tuples that aggregate items from each iterable by position.

33
New cards

How is map(func, iterable) commonly used?

Applies func to each item, producing an iterator of results.

34
New cards

What does filter(func, iterable) output?

An iterator with items for which func(item) is true.

35
New cards

What does any(iterable) test?

Returns True if at least one element is truthy.

36
New cards

What does all(iterable) verify?

Returns True only if every element is truthy.

37
New cards

What iterator is produced by reversed(seq)?

An iterator that yields the elements of seq in reverse order.

38
New cards

How does deque.appendleft(x) differ from deque.append(x)?

appendleft adds x to the left end; append adds to the right end.

39
New cards

What happens when deque.popleft() is called?

Removes and returns the leftmost item of the deque.

40
New cards

How does deque.extend(iterable) behave?

Adds all elements of iterable to the right side of the deque.

41
New cards

What is the effect of deque.rotate(n)?

Rotates n steps to the right (left if n is negative).

42
New cards

What does heapq.heapify(lst) accomplish?

Reorders lst in-place into a min-heap structure.

43
New cards

When would you use heapq.heappush(heap, item)?

To push item onto the heap while maintaining heap order.

44
New cards

What is returned by heapq.heappop(heap)?

The smallest item from the heap, after removing it.

45
New cards

How does heapq.nlargest(n, iterable) work?

Returns a list with the n largest elements from iterable.

46
New cards

What does heapq.heapreplace(heap, item) do?

Pops and returns smallest item, then pushes new item onto heap.

47
New cards

What is collections.Counter(iterable) useful for?

Counts the frequency of elements, returning a dict-like object.

48
New cards

How does collections.defaultdict(type) differ from dict?

Automatically creates default values of the given type for missing keys.

49
New cards

Why use collections.OrderedDict?

Maintains insertion order of keys (standard dicts do since Python 3.7, but OrderedDict adds extra methods).

50
New cards

What does itertools.product(*iterables) generate?

The Cartesian product of input iterables as tuples.

51
New cards

How does itertools.permutations(iterable, r) differ from combinations?

Permutations consider order; combinations do not.

52
New cards

What does itertools.combinations(iterable, r) return?

r-length subsequences of elements in sorted order, without replacement.

53
New cards

Why use itertools.accumulate(iterable)?

Produces running totals (or results of another binary function).

54
New cards

What does itertools.groupby(iterable) accomplish?

Groups consecutive identical elements after optional sorting/key-func.

55
New cards

How does itertools.chain(*iterables) help iteration?

Flattens multiple iterables into a single sequential iterator.

56
New cards

What is math.gcd(a, b) used for?

Computes the greatest common divisor of a and b.

57
New cards

How does math.lcm(a, b) differ from gcd?

Returns the least common multiple of a and b.

58
New cards

What does math.factorial(n) compute?

n! (the product of all positive integers ≤ n).

59
New cards

When would you call math.sqrt(x)?

To obtain the square root of x as a float.

60
New cards

What is math.ceil(x) contrasted with math.floor(x)?

ceil rounds x up to the nearest integer; floor rounds down.

61
New cards

What do math.comb(n, k) and math.perm(n, k) calculate?

comb gives the number of combinations; perm gives the number of permutations.

62
New cards

How can x & (x - 1) be used with powers of two?

It clears the lowest set bit, yielding 0 if and only if x is a power of 2.

63
New cards

What does the << operator perform in Python?

A left bit shift, equivalent to multiplying by 2**n.

64
New cards

How is the ^ (XOR) operator handy in coding interviews?

It can isolate unique/non-duplicated numbers in pairs-of-duplicates arrays.

65
New cards

What effect does the ~ operator have on an integer?

Bitwise NOT: flips every bit (two’s-complement).

66
New cards

How does @lru_cache(maxsize=None) aid recursion?

Memoizes function calls, caching results to avoid recomputation.

67
New cards

Why call sys.setrecursionlimit(n)?

To raise the maximum depth of the Python call stack for deep recursion.

68
New cards

What does (a, b) = (b, a) achieve?

Swaps the values of a and b without a temporary variable.

69
New cards

Explain a, *rest = iterable destructuring.

Assigns the first element to a and the remaining elements as a list to rest.

70
New cards

Give the pattern for a list comprehension with a condition.

[x for x in iterable if condition].

71
New cards

How is a dictionary comprehension written?

{k: v for k, v in iterable}.

72
New cards

What does "if not lst:" check in Pythonic code?

Tests whether the list lst is empty (or falsy).

73
New cards

Why use -value with heapq to create a max-heap?

Pushing negative values into a min-heap makes it behave like a max-heap.

74
New cards

How can you reverse a string s most Pythonically?

''.join(reversed(s)) or s[::-1].

75
New cards

How do you sort a dictionary by its values?

sorted(dict.items(), key=lambda x: x[1]).

76
New cards

What is a common fast pattern for reading space-separated ints?

list(map(int, input().split())).

77
New cards

How are type hints added to a function returning int from List[int]?

def func(nums: List[int]) -> int: