Top 20 Python Tips and Tricks with Code Examples

Aspersh Upadhyay
5 min readJun 14, 2024

--

Python is a versatile and powerful programming language that’s widely used for web development, data analysis, artificial intelligence, scientific computing, and more. Whether you’re a beginner or an experienced developer, there’s always something new to learn in Python. In this article, we’ll explore some valuable tips and tricks that can help you write more efficient, readable, and effective Python code. Each tip is accompanied by a code example to illustrate its application.

image by: Author

1. List Comprehensions

List comprehensions provide a concise way to create lists. They are more readable and faster than traditional for-loop methods.

Example:

# Traditional for-loop method
squares = []
for i in range(10):
squares.append(i ** 2)

# List comprehension method
squares = [i ** 2 for i in range(10)]
print(squares)

2. Dictionary Comprehensions

Similar to list comprehensions, dictionary comprehensions allow for more concise and readable dictionary creation.

Example:

# Traditional method
squared_dict = {}
for num in range(10):
squared_dict[num] = num ** 2

# Dictionary comprehension method
squared_dict = {num: num ** 2 for num in range(10)}
print(squared_dict)

3. Using Enumerate

The enumerate function adds a counter to an iterable, providing both index and value during iteration.

Example:

# Traditional method
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(i, fruits[i])

# Using enumerate
for i, fruit in enumerate(fruits):
print(i, fruit)

4. Zip Function

The zip function is useful for combining multiple iterables, such as lists, into a single iterable of tuples.

Example:

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)

5. F-Strings for String Formatting

Introduced in Python f-strings provide a more readable and concise way to format strings.

Example:

name = "Alice"
age = 25
# Traditional method
print("Hello, my name is {} and I am {} years old.".format(name, age))

# Using f-strings
print(f"Hello, my name is {name} and I am {age} years old.")

6. Unpacking Iterables

Python allows for the unpacking of iterables, making it easy to assign values to multiple variables in a single statement.

Example:

# Unpacking a list
numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c)

# Unpacking a tuple
person = ('Alice', 25, 'Engineer')
name, age, profession = person
print(name, age, profession)

7. Using *args and **kwargs

These special syntax elements allow you to pass a variable number of arguments to a function, enhancing its flexibility.

Example:

def example_function(arg1, *args, **kwargs):
print("arg1:", arg1)
print("args:", args)
print("kwargs:", kwargs)

example_function(1, 2, 3, 4, name="Alice", age=25)

8. Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They are often used for short, simple functions.

Example:

# Traditional function
def add(x, y):
return x + y

# Lambda function
add = lambda x, y: x + y
print(add(2, 3))

9. Using map and filter

The map function applies a function to all items in an input list, while the filter function creates a list of elements for which a function returns true.

Example:

# Using map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)

# Using filter
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)

10. Context Managers

Context managers are used to manage resources, such as file operations, ensuring proper acquisition and release of resources.

Example:

# Traditional method
file = open('example.txt', 'w')
try:
file.write('Hello, world!')
finally:
file.close()

# Using a context manager
with open('example.txt', 'w') as file:
file.write('Hello, world!')

11. Handling Exceptions with try, except, else, and finally

Exception handling in Python can be fine-tuned using else and finally blocks along with try and except.

Example:

try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful")
finally:
print("This is executed no matter what")

12. Using Generators

Generators allow you to iterate over data without storing it all in memory at once. They are created using functions and the yield keyword.

Example:

def generate_numbers(n):
for i in range(n):
yield i

for num in generate_numbers(5):
print(num)

13. Merging Dictionaries

In Python 3.9 and later, you can merge dictionaries using the | operator.

Example:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
print(merged_dict)

14. Using itertools

The itertools module provides functions for creating iterators for efficient looping.

Example:

import itertools 

# Infinite iterator
counter = itertools.count(start=1, step=2)
for _ in range(5):
print(next(counter))

# Combinations
items = ['a', 'b', 'c']
combinations = list(itertools.combinations(items, 2))
print(combinations)

15. Using collections

The collections module offers specialized data structures such as Counter, defaultdict, and deque.

Example:

from collections import Counter, defaultdict, deque 

# Counter
word_counts = Counter('abracadabra')
print(word_counts)

# defaultdict
default_dict = defaultdict(int)
default_dict['key'] += 1
print(default_dict)

# deque
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)

16. Using functools

The functools module includes higher-order functions that act on or return other functions.

Example:

from functools import lru_cache

# Using lru_cache to cache results of expensive function calls
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

print([fibonacci(n) for n in range(10)])

17. Advanced String Manipulation with re

The re module allows for advanced string operations using regular expressions.

Example:

import re

text = "The rain in Spain stays mainly in the plain"
pattern = re.compile(r'\bin\b')
matches = pattern.findall(text)
print(matches)

# Replacing patterns
result = re.sub(r'Spain', 'Italy', text)
print(result)

18. Type Hinting

Type hinting improves code readability and helps with debugging by explicitly specifying the expected data types of function arguments and return values.

Example:

def greeting(name: str) -> str:
return f"Hello, {name}"

print(greeting("Alice"))

19. Using dataclasses

The dataclasses module provides a decorator and functions for automatically adding special methods to classes.

Example:

from dataclasses import dataclass

@dataclass
class Person:
name: str
age: int

p = Person(name="Alice", age=25)
print(p)

20. Advanced Argument Parsing with argparse

The argparse module makes it easy to write user-friendly command-line interfaces.

Example:

import argparse

parser = argparse.ArgumentParser(description="A simple argument parser")
parser.add_argument('name', type=str, help='Your name')
parser.add_argument('--age', type=int, help='Your age', default=25)
args = parser.parse_args()

print(f"Hello, {args.name}. You are {args.age} years old.")

Conclusion

Python’s simplicity and readability make it a favorite among developers. By incorporating these tips and tricks into your programming practice, you can write more efficient, readable, and maintainable code. Whether you’re manipulating data structures, formatting strings, or handling exceptions, these techniques will help you leverage the full power of Python. Keep experimenting and exploring to continually enhance your Python skills.

Gain access to exclusive insights and industry updates by following Aspersh Upadhyay — join my community and stay informed.

If you’re interested in learning resources related to Data Science, Machine Learning, Python, SQL and more. Join my telegram channel Bits of Data Science. Connect with me on LinkedIn.

--

--

Aspersh Upadhyay

📊Learn Data Analytics | AI | ML | DL | Python🐍1️⃣ Get Free Learning Resources : t.me/bitsofds 2️⃣ Daily Tips: instagram.com/bitsofds