Member-only story

Write Better Codes: 100+ Tips to Make Your Codes More Pythonic

btd
16 min readDec 26, 2023

--

Photo by Mingwei Lim on Unsplash

Writing “Pythonic” code means adhering to the idioms and conventions of the Python language. Pythonic code is often more readable, concise, and follows the principles of the Python community. Here are some tips to make your code more Pythonic:

1. List Comprehensions:

List comprehensions provide a concise way to create lists.

# Non-Pythonic
squares = []
for x in range(10):
squares.append(x**2)

# Pythonic
squares = [x**2 for x in range(10)]

2. Use Built-in Functions:

Python has many built-in functions that can simplify your code.

# Non-Pythonic
total = 0
for num in numbers:
total += num

# Pythonic
total = sum(numbers)

3. Enumerate:

enumerate provides both the index and value during iteration.

# Non-Pythonic
for i in range(len(items)):
item = items[i]
print(i, item)

# Pythonic
for i, item in enumerate(items):
print(i, item)

4. Zip:

zip combines multiple iterables into tuples.

# Non-Pythonic
for i in range(len(keys)):
key = keys[i]
value = values[i]
print(key, value)

# Pythonic
for…

--

--

btd
btd

No responses yet