A Cheat Sheet 📜 to revise Python syntax in less time. Particularly useful for solving Data Structure and Algorithmic problems or a quick overview before an interview.
Click here for similar Java Resource (not made by me)
Get a PDF of this sheet at the end.
Leave a ⭐ if you like the cheat sheet (contributions welcome!)
nums= [1,2,3]
# Common Operationsnums.index(1) # Find indexnums.append(1) # Add to endnums.insert(0,10) # Add 10 from left (at index 0 which is start)nums.remove(3) # Remove valuenums.pop() # Remove & return last elementnums.sort() # In-place sort (TimSort: O(n log n))nums.reverse() # In-place reversenums.copy() # Return shallow copy# List Slicingnums[start:stop:step] # Generic slice syntaxnums[-1] # Last itemnums[::-1] # Reverse listnums[1:] # Everything after index 1nums[:3] # First three elementsd= {'a':1, 'b':2}
# Essential Operationsd.get('key', default) # Safe access with defaultd.setdefault('key', 0) # Set if missingd.items() # Key-value pairsd.keys() # Just keysd.values() # Just valuesd.pop(key) # Remove and return valued.update({key: value}) # Batch update# Advanced Usagefromcollectionsimportdefaultdictd=defaultdict(list) # Auto-initialize missing keysd=defaultdict(int) # Useful for countingfromcollectionsimportCounter# Initializec=Counter(['a','a','b']) # From iterablec=Counter("hello") # From string# Operationsc.most_common(2) # Top 2 frequent elementsc['a'] +=1# Increment countc.update("more") # Add counts from iterablec.total() # Sum of all countsc.elements() # Returns an iterator over elements repeating c.subtract("ole") # Subtract counts from iterable (can go negative)fromcollectionsimportdeque# Perfect for BFS - O(1) operations on both endsd=deque()
d.append(1) # Add rightd.appendleft(2) # Add leftd.pop() # Remove rightd.popleft() # Remove leftd.extend([1,2,3]) # Extend rightd.extendleft([1,2,3])# Extend leftd.rotate(n) # Rotate n steps right (negative for left)importheapq# MinHeap Operations - All O(log n) except heapifynums= [3,1,4,1,5]
heapq.heapify(nums) # Convert to heap in-place: O(n)heapq.heappush(nums, 2) # Add element: O(log n)smallest=heapq.heappop(nums) # Remove smallest: O(log n)# MaxHeap Trick: Multiply by -1nums= [-xforxinnums] # Convert to maxheap: O(n)heapq.heapify(nums) # O(n)largest=-heapq.heappop(nums) # Get largest: O(log n)# Advanced Operationsk_largest=heapq.nlargest(k, nums) # O(n * log k)k_smallest=heapq.nsmallest(k, nums) # O(n * log k)# Custom Priority Queueheap= []
heapq.heappush(heap, (priority, item)) # Sort by prioritys= {1,2,3}
# Common Operationss.add(4) # Add elements.remove(4) # Remove (raises error if missing)s.discard(4) # Remove (no error if missing)s.pop() # Remove and return arbitrary element# Set Operationsa.union(b) # Elements in a OR ba.intersection(b) # Elements in a AND ba.difference(b) # Elements in a but NOT in ba.symmetric_difference(b) # Elements in a OR b but NOT botha.issubset(b) # True if all elements of a are in ba.issuperset(b) # True if all elements of b are in a# Tuples are immutable listst= (1, 2, 3, 1)
# Essential Operationst.count(1) # Count occurrences of valuet.index(2) # Find first index of value# Useful Patternsx, y= (1, 2) # Tuple unpackingcoords= [(1,2), (3,4)] # Tuple in collectionss="hello world"# Essential Methodss.split() # Split on whitespaces.split(',') # Split on commas.strip() # Remove leading/trailing whitespaces.lower() # Convert to lowercases.upper() # Convert to uppercases.isalnum() # Check if alphanumerics.isalpha() # Check if alphabetics.isdigit() # Check if all digitss.find('sub') # Index of substring (-1 if not found)s.count('sub') # Count occurrencess.replace('old', 'new') # Replace all occurrences# ASCII Conversionord('a') # Char to ASCII (97)chr(97) # ASCII to char ('a')# Join Lists''.join(['a','b']) # Concatenate list elements# Iteration Helpersenumerate(lst) # Index + value pairszip(lst1, lst2) # Parallel iterationmap(fn, lst) # Apply function to all elementsfilter(fn, lst) # Keep elements where fn returns Trueany(lst) # True if any element is Trueall(lst) # True if all elements are True# Binary Search (import bisect)bisect.bisect(lst, x) # Find insertion pointbisect.bisect_left(lst, x)# Find leftmost insertion pointbisect.insort(lst, x) # Insert maintaining sort# Type Conversionint('42') # String to intstr(42) # Int to stringlist('abc') # String to list''.join(['a','b']) # List to stringset([1,2,2]) # List to set# Mathabs(-5) # Absolute valuepow(2, 3) # Powerround(3.14159, 2) # Round to decimalsfromfunctoolsimportcmp_to_keydefcompare(item1, item2):
# Return -1: item1 comes first# Return 1: item2 comes first# Return 0: items are equalifitem1<item2:
return-1elifitem1>item2:
return1return0# Sort using custom comparisonsorted_list=sorted(items, key=cmp_to_key(compare))# Basic multiple inputx, y=input("Enter two values: ").split()
# Multiple integersx, y=map(int, input("Enter two numbers: ").split())
# List of integersnums=list(map(int, input("Enter numbers: ").split()))
# Multiple inputs with custom separatorvalues=input("Enter comma-separated values: ").split(',')
# List comprehension methodx, y= [int(x) forxininput("Enter two numbers: ").split()]importmath# Constantsmath.pi# 3.141592653589793math.e# 2.718281828459045# Common Functionsmath.ceil(2.3) # 3 - Smallest integer greater than xmath.floor(2.3) # 2 - Largest integer less than xmath.gcd(a, b) # Greatest common divisormath.log(x, base) # Logarithm with specified basemath.sqrt(x) # Square rootmath.pow(x, y) # x^y (prefer x ** y for integers)# Trigonometrymath.degrees(rad) # Convert radians to degreesmath.radians(deg) # Convert degrees to radians# Binary representationbin(10) # '0b1010'format(10, 'b') # '1010' (without prefix)# Division and Modulodivmod(10, 3) # (3, 1) - returns (quotient, remainder)# Negative number handlingx=-3y=2print(x//y) # -2 (floor division)print(int(x/y)) # -1 (preferred for negative numbers)print(x%y) # 1 (Python's modulo with negative numbers)defbinary_search(arr, target):
""" Find target in sorted array using binary search. Args: arr: Sorted list of numbers target: Number to find Returns: Index of target or -1 if not found """pass# Use assertions for edge casesassertbinary_search([], 1) ==-1, "Empty array should return -1"assertbinary_search([1], 1) ==0, "Single element array should work"- Integer Division:
# Use int() for consistent negative number handlingprint(-3//2) # Returns -2print(int(-3/2)) # Returns -1 (usually desired)- Default Dictionaries:
# Prefer defaultdict for frequency countingfromcollectionsimportdefaultdictfreq=defaultdict(int)
forxinlst:
freq[x] +=1# No KeyError if x is new- Heap Priority:
# For custom priority in heapq, use tuplesheap= []
heapq.heappush(heap, (priority, item))- List Comprehension:
# Often clearer than map/filtersquares= [x*xforxinrange(10) ifx%2==0]- String Building:
# Use join() instead of += for stringschars= ['a', 'b', 'c']
word=''.join(chars) # More efficient- Using Sets for Efficiency:
# O(1) lookup for contains operationsseen=set()
ifxinseen: # Much faster than list lookupprint("Found!")- Custom Sort Keys:
# Sort by length then alphabeticallywords.sort(key=lambdax: (len(x), x))- Default Arguments Warning:
# Don't use mutable defaultsdefbad(lst=[]): # This can cause bugslst.append(1)
returnlstdefgood(lst=None): # Do this insteadiflstisNone:
lst= []
lst.append(1)
returnlstMade with ❤️ for fellow leetcoders.





