Collect 200 Python tricks
1. Basic Tricks
Swapping Variables:
a, b = b, aMultiple Assignment:
a, b, c = 1, 2, 3Unpacking Lists/Tuples:
a, *b, c = [1, 2, 3, 4]Inline If-Else:
result = a if condition else bString Reversal:
reversed_string = my_string[::-1]
2. List and Dictionary Comprehensions
Simple List Comprehension:
[x**2 for x in range(10)]Filtering with List Comprehension:
[x for x in range(10) if x % 2 == 0]Nested Comprehensions:
matrix = [[i for i in range(5)] for _ in range(3)]Dictionary Comprehension:
{i: i**2 for i in range(5)}Set Comprehension:
{i for i in range(10) if i % 2 == 0}
3. Lambda Functions
Basic Lambda:
add = lambda x, y: x + ySorting with Lambda:
sorted_list = sorted(my_list, key=lambda x: x[1])Filtering with Lambda:
filtered = filter(lambda x: x % 2 == 0, my_list)Mapping with Lambda:
mapped = map(lambda x: x * 2, my_list)
4. Advanced Data Structures
Default Dictionary:
Counter:
Named Tuples:
Deque for Efficient Queues:
5. File Handling
Context Manager:
Reading a File Line by Line:
Writing to a File:
6. Pythonic Code Practices
Enumerate:
Zip to Iterate in Parallel:
List Flattening:
Using
_for Ignoring Values:
7. Error Handling
Basic Try-Except:
Finally Clause:
Else in Try-Except:
8. Working with Modules
Importing Modules:
Importing with Aliases:
Reloading Modules (for development):
9. Function Tricks
Default Arguments:
Arbitrary Arguments:
Functions as First-Class Citizens:
Recursive Functions:
10. Decorators
Basic Decorator:
Decorator with Arguments:
11. Generators
Basic Generator:
Generator Expressions:
12. Handling Time and Date
Current Date and Time:
Time Delta:
Formatting Date and Time:
Parsing Date Strings:
13. Useful Built-in Functions
All and Any:
Sum of Elements:
Max and Min:
Reversing an Iterable:
14. Working with JSON
Loading JSON:
Dumping JSON:
Pretty Printing JSON:
15. Object-Oriented Programming
Basic Class Definition:
Inheritance:
Class and Static Methods:
16. Miscellaneous
Ternary Operators:
Chaining Comparisons:
Last updated