DEV Community

Cover image for 10 Python Tricks Every Developer Should Know
Gulshan Kumar
Gulshan Kumar

Posted on

10 Python Tricks Every Developer Should Know

Python is celebrated for its readability and simplicity, but beneath its clean syntax lie powerful features that can make your code more elegant, efficient, and Pythonic. Here are ten handy Python tricks every developer should have in their toolkit.

1. Swapping Variables in One Line

a, b = b, a
Enter fullscreen mode Exit fullscreen mode

Python allows you to swap variables without needing a temporary variable.

2. List Comprehensions with Conditionals
Build lists concisely with conditions:

squares = [x**2 for x in range(10) if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode

3. Unpacking Iterables with the * Operator
You can easily unpack parts of a list:

first, *middle, last = [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

4. Using zip to Iterate Over Multiple Iterables

names = ['Alice', 'Bob']
ages = [25, 30]

for name, age in zip(names, ages):
    print(name, age)
Enter fullscreen mode Exit fullscreen mode

5. Merging Dictionaries with ** Operator (Python 3.5+)

d1 = {'a': 1}
d2 = {'b': 2}
merged = {**d1, **d2}
Enter fullscreen mode Exit fullscreen mode

6. Using enumerate to Get Index and Value

for index, value in enumerate(['a', 'b', 'c']):
    print(index, value)
Enter fullscreen mode Exit fullscreen mode

7. Using collections.Counter for Counting

from collections import Counter

counts = Counter('abracadabra')
print(counts)
Enter fullscreen mode Exit fullscreen mode

8. Using set to Remove Duplicates

unique = list(set([1, 2, 2, 3, 3, 3]))
Enter fullscreen mode Exit fullscreen mode

9. Ternary Conditional Expressions

status = 'Even' if x % 2 == 0 else 'Odd'
Enter fullscreen mode Exit fullscreen mode

10. Joining Strings Efficiently

words = ['Python', 'is', 'fun']
sentence = ' '.join(words)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)