🐍 Python Pro Tips That I Wish I Use More...
Hisham Elamir
Posted on July 22, 2024
As a Python enthusiast, I'm always on the lookout for ways to write cleaner, more efficient code. Here are some of my favorite Python tricks that can help you become a more effective programmer:
- List Comprehensions: Create lists with concise, readable one-liners.
even_numbers = [x for x in range(10) if x % 2 == 0 and x != 0]
- F-strings: Format strings easily and readably (Python 3.6+).
name, age = "John", 30
print(f"I'm {name} and I'm {age} years old.")
- Enumerate: Get both index and value when iterating.
for index, value in enumerate(["a", "b", "c"]):
print(f"Index: {index}, Value: {value}")
- Unpacking: Assign multiple variables in one line.
a, b, c = 1, 2, 3
- Slicing: Manipulate sequences efficiently.
my_list = [0, 1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
-
Use Counter: use
collections.Counter
for counting elements.
from collections import Counter
my_list = [1, 1, 2, 3, 3, 3, 4]
print(Counter(my_list))
-
Flattening: Flatten nested lists with
itertools.chain
.
import itertools
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = list(itertools.chain.from_iterable(nested_list))
-
Iterate Over Many: Use
zip()
to iterate over multiple lists simultaneously.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
These tricks can help you write more Pythonic code and boost your productivity. What are your favorite Python tips? Share in the comments below!
Thanks for reading.
💖 💪 🙅 🚩
Hisham Elamir
Posted on July 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.