Python: Tips And Tricks To Write Better Code
Writing better code not only makes it look good but also increases the performance of execution. With newer versions and feature supports, python has provided various coding flexibility and performance optimizations. Since, python is a high level language, coding with best practices will make the execution faster, better and more suitable.
How to write better python code ?
Using latest features and considering time/space complexity while coding makes the python code better. Here are some tips for writing better python code.
- Iterate with enumerate instead of
range(len(x))
. - Use list comprehension rather than using raw for loops.
- Sort complex iterables with
sorted()
. - Store unique values with Sets.
- Save memory with Generators.
- Define default values in Dictionary with
.get()
and.setdefault()
. - Count hashable objects
collections.Counter
. - Format strings with f-strings.
- Concatenate strings with
.join()
. - Merge Dictionaries with
{**d1, **d2}
. - Simplify if statement with
if x in [a, b, c]
.
These were some of the best practices you should apply in your coding. Let’s see the implementations one by one.
Iterate with enumerate instead of range(len(x))
list = [10, 20, 30, 40, 50]
#using range(len(x))
for i in range(len(list)):
print(list[i])
#using enumerate
for index, value in enumerate(list):
print('index: ', index, 'value: ', value)
Using list comprehension rather than raw for loop
list = [10, 20, 30, 40, 50]
#using raw for loop
for i in range(len(list)):
list[i] = list[i]*list[i]
print(list)
#using list comprehension
list = [value*value for index, value in enumerate(list)]
print(list)
Sort complex iterables with sorted()
list = [10, 30, 20, 50, 40]
#sort in accending order
accending = sorted(list)
print(accending)
#sort in descending order
descending = sorted(list, reverse=True)
print(descending)
Store unique values with Set
list = [10, 30, 10, 20, 30, 20, 50, 50, 40, 30]
#find unique items only
unique_items = set(list)
print(unique_items)
Save memory with Generators
list = [i for i in range(10000)]
print(sum(list))
#using generator <-- does lazily so less memory
list = (i for i in range(10000))
print(sum(list))
Define default values in Dictionary using .get() and .setdefault()
dict = {"one": 1, "two": 2, "three": 3}
#following will raise error because key 'four' does not have default value
#print(dict.get("four"))
print(dict.get("four", 4))
#default value can be set using .setdefault() as well
dict.setdefault("five", 5)
print(dict.get("five"))
Count hashable objects using collections.Counter
from collections import Counter
list = [1, 1, 1, 2, 3, 2, 2, 4, 5, 4, 5, 3]
counter = Counter(list)
print(counter)
Format strings with f-strings
target = "World !"
str = f"Hello {target}"
print(str)
Concatenate strings with .join()
str = ["Welcome", "to", "the", "club", "!"]
str = " ".join(str)
print(str)
Merge dictionaries with {**d1, **d2}
dict1 = {"one": 1, "two": 2}
dict2 = {"three": 3, "four": 4}
merged = {**dict1, **dict2}
print(merged)
Simplify if statement with if x in [a, b, c]
item_color = "red"
#BAD
if item_color == "black" or item_color == "red" or item_color == "green":
print("color found !")
#BETTER
if item_color in ["black", "red", "green"]:
print("color found !")
So, these were some noticeable good practices in python programming but you will find much more if you explore for sure. Multiply (learn, code) and improve yourself.
HAPPY CODING !