10 Python Shortcuts
List Comprehensions
Instead of using loops to create lists, use list comprehensions for readable code.
numbers = [x for x in range(10)]
Dictionary Comprehensions
Similar to list comprehensions, you can create dictionaries in a compact way.
squares = {x: x*x for x in range(5)}
Multiple Assignment
Assign values to multiple variables in a single line.
a, b = 10, 20
Swapping Values
Swap the values between two variables without using a temporary variable.
a, b = b, a
Conditional Assignement
Use the ternary conditional expression for concise assignments based on conditions.
value = x if x > 0 else 0
String Formatting
Use f-strings for concise and readable string formatting.
name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
Unpacking Iterables
Unpack elements from iterables like lists or tuples directly into variables.
numbers = [1, 2, 3]
a, b, c = numbers
Enumerate
Iterate over a sequence while keeping track of the index.
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
Zip
Combine multiple sequences into pairs using zip
.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 22]
for name, age in zip(names, ages):
print(f"Name: {name}, Age: {age}")
Default Dictionary Values
Use collections.defaultdict
to set default values for dictionary keys.
from collections import defaultdict
counts = defaultdict(int)
counts["apples"] += 1 # No need to check if key exists