🐍 Python One-Page Tricks
🔹 1. Swap Variables (No Temp Variable)
a, b = 5, 10
a, b = b, a
🔹 2. Multiple Assignments
a = b = c = 100
x, y, z = 1, 2, 3
🔹 3. Reverse a String / List
text = "python"
print(text[::-1])
🔹 4. List Comprehension (Short Loop)
squares = [x*x for x in range(5)]
🔹 5. Conditional (Ternary Operator)
result = "Even" if num % 2 == 0 else "Odd"
🔹 6. Remove Duplicates
nums = [1,2,2,3,4]
nums = list(set(nums))
🔹 7. Join Strings Efficiently
words = ["I", "love", "Python"]
sentence = " ".join(words)
🔹 8. Count Frequency
from collections import Counter
print(Counter("banana"))
🔹 9. Zip Lists Together
names = ["A", "B"]
marks = [90, 80]
print(list(zip(names, marks)))
🔹 10. Get Max/Min with Key
students = {"A": 90, "B": 80}
top = max(students, key=[Link])
🔹 11. Flatten List
nested = [[1,2],[3,4]]
flat = [item for sub in nested for item in sub]
🔹 12. Check All / Any
all([True, True]) # True
any([False, True]) # True
🔹 13. Read File in One Line
data = open("[Link]").read()
🔹 14. Lambda Function (Quick Function)
add = lambda a, b: a + b
🔹 15. Dictionary Merge
d1 = {"a":1}
d2 = {"b":2}
d = {**d1, **d2}
🔹 16. Get Unique Elements (Order Preserved)
nums = [1,2,2,3]
unique = list([Link](nums))
🔹 17. Time Your Code
import time
start = [Link]()
# code
print([Link]() - start)
🔹 18. Quick Sort List
nums = [3,1,4]
[Link]() # original
sorted_nums = sorted(nums) # new list
🔹 19. Unpack Values
a, *b = [1,2,3,4]
# a=1, b=[2,3,4]
🔹 20. Infinite Loop (Controlled)
while True:
break # exit when needed