Some Python clean code examples.
Bad code
items = [1, 3, 5]
for i in range(len(items)):
print(items[i])
Good code
items = [1, 3, 5]
for item in items:
print(item)
Bad code
items = [1, 3, 5]
for i in range(len(items)):
print(i, items[i])
Good code
items = [1, 3, 5]
for i, item in enumerate(items):
print(i, item)
Bad code
items = [1, 3, 5]
other_items = [2, 4, 6]
for i in range(len(items)):
print(items[i], other_items[i])
Good code
items = [1, 3, 5]
other_items = [2, 4, 6]
for item, other_item in zip(items, other_items):
print(item, other_item)
Bad code
items = [1, 3, 5]
other_items = []
for item in items:
other_items.append(item * item)
Good code
items = [1, 3, 5]
other_items = [item * item for item in items]
Bad code
items = [1, 3, 5]
items_dict = {}
for i, item in enumerate(items):
items_dict[i] = item
Good code
items = [1, 3, 5]
items_dict = {i:item for i, item in enumerate(items)}
Bad code
items = [1, 2, 4, 2, 3, 5, 3, 1, 2, 3, 5, 6, 4]
d = dict()
for item in items:
if item not in d:
d[item] = 1
else:
d[item] += 1
Good code
from collections import Counter
items = [1, 2, 4, 2, 3, 5, 3, 1, 2, 3, 5, 6, 4]
d = Counter()
for item in items:
d[item] += 1
Better code
from collections import Counter
items = [1, 2, 4, 2, 3, 5, 3, 1, 2, 3, 5, 6, 4]
d = Counter(items)
Bad code
f = open("some_file")
data = f.read()
f.close()
Good code
with open("some_file") as f:
data = f.read()