1. Use List Comprehensions for Simple Loops
(Replaces verbose
for loops for creating lists.)Cluttered Way:
squares = []
for i in range(10):
squares.append(i * i)
Clean Way:
squares = [i * i for i in range(10)]
2. Use
enumerate for Index and Value(Avoids manual index tracking with
range(len(...))).)Cluttered Way:
items = ['a', 'b', 'c']
for i in range(len(items)):
print(i, items[i])
Clean Way:
items = ['a', 'b', 'c']
for i, item in enumerate(items):
print(i, item)
3. Use Context Managers for Resources
(Ensures resources like files are properly closed, even if errors occur.)
Cluttered Way:
f = open('my_file.txt', 'w')
try:
f.write('hello world')
finally:
f.close()Clean Way:
with open('my_file.txt', 'w') as f:
f.write('hello world')4. Use Dictionary
.get() for Safe Key Access(Prevents
KeyError and avoids verbose if key in dict checks.)Cluttered Way:
my_dict = {'name': 'Alice'}
if 'age' in my_dict:
age = my_dict['age']
else:
age = 0Clean Way:
my_dict = {'name': 'Alice'}
age = my_dict.get('age', 0)5. Use F-Strings for Formatting
(More readable and often faster than other string formatting methods.)
Cluttered Way:
name = "Bob"
age = 30
message = "Hello, " + name + "! You are " + str(age) + " years old."
# Or: message = "Hello, {}! You are {} years old.".format(name, age)
Clean Way:
name = "Bob"
age = 30
message = f"Hello, {name}! You are {age} years old."
6. Use Unpacking to Swap Variables
(A concise, Pythonic way to swap values without a temporary variable.)
Cluttered Way:
a = 5
b = 10
temp = a
a = b
b = temp
Clean Way:
a = 5
b = 10
a, b = b, a
7. Check for Empty Sequences Correctly
(Leverages Python's "truthiness" for more readable code.)
Cluttered Way:
my_list = []
if len(my_list) == 0:
print("List is empty!")
Clean Way:
my_list = []
if not my_list:
print("List is empty!")
8. Use Underscores for Unused Variables
(Signals to other developers that a variable is intentionally ignored.)
Cluttered Way:
# 'i' is created but never used
for i in range(5):
print("Hello")
Clean Way:
for _ in range(5):
print("Hello")
9. Chain Comparison Operators
(Makes numerical range checks more intuitive and readable.)
Cluttered Way:
x = 10
if x > 5 and x < 15:
print("x is between 5 and 15")
Clean Way:
x = 10
if 5 < x < 15:
print("x is between 5 and 15")
10. Return from a Function Early
(Reduces nesting and improves readability by handling edge cases or invalid states first.)
Cluttered Way:
def process_data(data):
if data is not None:
if isinstance(data, list) and len(data) > 0:
# ... deep nested logic here ...
print("Processing data...")
return "Done"
else:
return "Error: Invalid data format."
else:
return "Error: No data provided."
Clean Way: