1. Unpacking Multiple Values
Unpacking simplifies handling multiple values in lists, tuples, or dictionaries.
a, b, c = [1, 2, 3]print(a, b, c) # Output: 1 2 3
Explanation:
- You assign values from the list [1, 2, 3] directly to a, b, and c. No need for index-based access.
2. Swap Two Variables Without a Temp Variable
Python allows swapping variables in one line.
x, y = 5, 10x, y = y, xprint(x, y) # Output: 10 5
Explanation:
- Python internally uses tuple packing/unpacking to achieve swapping in one line.
3. List Comprehension for One-Liners
Condense loops into one-liners using list comprehensions.
squares = [x*x for x in range(5)]print(squares) # Output: [0, 1, 4, 9, 16]
Explanation:
- Instead of a loop, you create a list of squares with concise syntax [x*x for x in range(5)].
4. Use zip to Pair Two Lists
Combine two lists element-wise into tuples using zip.
names = ["Alice", "Bob"]scores = [85, 90]
pairs = list(zip(names, scores))print(pairs) # Output: [('Alice', 85), ('Bob', 90)]
Explanation:
- zip pairs the first elements of both lists, then the second elements, and so on.
5. Dictionary Comprehension
Quickly create dictionaries from lists or ranges.
squares_dict = {x: x*x for x in range(5)}print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Explanation:
- {key: value for item in iterable} creates a dictionary where the key is x and the value is x*x.
6. Use enumerate to Track Indices
Get the index and value from an iterable in one loop.
fruits = ["apple", "banana", "cherry"]for index, fruit in enumerate(fruits):
print(index, fruit)
# Output:
# 0 apple
# 1 banana# 2 cherry
Explanation:
- enumerate returns both the index and the value during iteration.
7. Use *args and **kwargs in Functions
Handle a variable number of arguments in your functions.
def greet(*args, **kwargs): for name in args:
print(f"Hello, {name}!")
for key, value in kwargs.items():
print(f"{key}: {value}")
greet("Alice", "Bob", age=25, location="NYC")
# Output:
# Hello, Alice!
# Hello, Bob!
# age: 25# location: NYC
Explanation:
- *args: Collects positional arguments into a tuple.
- **kwargs: Collects keyword arguments into a dictionary.
These tricks save time and make your code concise. Which one is your favorite? 😊
0 Comments:
Post a Comment