11 Must Know Tips and Tricks to write better Python code

Vinicius Cardoso
3 min readMar 25, 2024

Hello everyone, today, I’ll share 11 tips that can instantly enhance the quality of your Python code, making it cleaner and more aligned with Python’s philosophy of simplicity and readability. These tips are designed to introduce you to best practices that you might not be using yet but should definitely consider incorporating into your work.

1. Iterate with Enumerate Instead of Range

The Pythonic way to iterate over a list while tracking the index and the item is to use enumerate instead of range(len()). This makes your code more readable and Pythonic.

Example:

# Less Pythonic
for i in range(len(my_list)):
if my_list[i] < 0:
my_list[i] = 0

# More Pythonic
for i, item in enumerate(my_list):
if item < 0:
my_list[i] = 0

2. Use List Comprehension for Conciseness

List comprehensions provide a concise way to create lists. They can make your code more readable and faster by reducing the lines of code while still being very powerful and flexible.

Example:

# Traditional approach
squared_numbers = []
for x in range(10):
squared_numbers.append(x ** 2)

# Using list comprehension
squared_numbers =…

--

--

Vinicius Cardoso

BSc. Computer Engineer, MSc. Student in Software Engineering