Python Shortcuts Cheat Sheet (with Examples)
Ternary / One-Line If-Else
Example: status = "Adult" if age >= 18 else "Minor"
Swapping Variables Without Temp
Example: a, b = b, a
List Comprehension
Example: [x*x for x in range(5)]
List Comprehension with Condition
Example: [x for x in range(10) if x % 2 == 0]
Flatten a 2D List
Example: [num for row in matrix for num in row]
Dictionary Comprehension
Example: {x: x*x for x in range(5)}
Set Comprehension
Example: {x for x in [1,2,2,3,4,4]}
Enumerate with Index
Example: for i, fruit in enumerate(fruits):
Zip Two Lists Together
Example: for name, score in zip(names, scores):
Lambda Functions
Example: square = lambda x: x * x
Sort List of Tuples by Second Value
Example: sorted(items, key=lambda x: x[1])
Check if a List is Empty
Example: if not mylist:
Multiple Conditions in One Line
Example: if 5 < x < 15:
Get Max/Min with Key
Example: max(words, key=len)
Join List of Strings
Example: " ".join(words)
List All Even Numbers
Example: list(range(0, 20, 2))
Unpack List into Variables
Example: a, b, c = [1, 2, 3]
*args and **kwargs
Example: def greet(*names, **details):