DEV Community

Hisham Elamir
Hisham Elamir

Posted on • Edited on

🐍 Python Pro Tips That I Wish I Use More...

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:

  1. List Comprehensions: Create lists with concise, readable one-liners.
even_numbers = [x for x in range(10) if x % 2 == 0 and x != 0]
Enter fullscreen mode Exit fullscreen mode
  1. 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.")
Enter fullscreen mode Exit fullscreen mode
  1. Enumerate: Get both index and value when iterating.
for index, value in enumerate(["a", "b", "c"]):
    print(f"Index: {index}, Value: {value}")
Enter fullscreen mode Exit fullscreen mode
  1. Unpacking: Assign multiple variables in one line.
a, b, c = 1, 2, 3
Enter fullscreen mode Exit fullscreen mode
  1. Slicing: Manipulate sequences efficiently.
my_list = [0, 1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
Enter fullscreen mode Exit fullscreen mode
  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))
Enter fullscreen mode Exit fullscreen mode
  1. 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))
Enter fullscreen mode Exit fullscreen mode
  1. 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")
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
sreno77 profile image
Scott Reno

Good tips!

Collapse
 
hisham_elamir profile image
Hisham Elamir

Thanks a lot for your kind comment. You will help me to continue 🚀👌