Python is a powerful and versatile language, but mastering its hidden tricks can take your skills to the next level. If you know these Python tricks, you’re absolutely a Python pro!
1. Swap Variables in One Line
No need for a temporary variable—swap values like a pro:
a, b = b, a
2. List Comprehensions for Quick Iterations
Instead of using loops, use list comprehensions:
squares = [x**2 for x in range(10)]
3. Use zip() to Pair Elements
Efficiently iterate over multiple lists in parallel:
names = ["Alice", "Bob", "Charlie"]ages = [25, 30, 35]
for name, age in zip(names, ages): print(name, age)
4. Dictionary Comprehension for Cleaner Code
Create dictionaries in a single line:
squares_dict = {x: x**2 for x in range(5)}
5. Use enumerate() Instead of Range-Based Loops
Instead of using range(len()), use enumerate():
items = ["apple", "banana", "cherry"]for index, item in enumerate(items, start=1): print(index, item)
6. Unpacking Multiple Values from a List
Assign multiple values effortlessly:
data = ["Python", 3.9, "Pro"]language, version, level = data
7. collections.Counter for Quick Frequency Count
Count occurrences in a list easily:
from collections import Counternums = [1, 2, 2, 3, 3, 3, 4]print(Counter(nums))
8. Use *args and **kwargs for Flexible Functions
Allow functions to accept any number of arguments:
def greet(*names): for name in names:
print(f"Hello, {name}!")greet("Alice", "Bob", "Charlie")
9. setdefault() for Handling Missing Keys
Avoid key errors when working with dictionaries:
data = {}data.setdefault("name", "Unknown")print(data["name"])
10. Use any() and all() for Logical Checks
Check conditions in one line:
numbers = [0, 1, 2, 3]print(any(numbers)) # True if any value is non-zeroprint(all(numbers)) # True if all values are non-zero
0 Comments:
Post a Comment