Python: Tips And Tricks To Write Better Code

Link Copied To Clipboard !

python-tips-and-tricks-for-better-coding Programming

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.

  1. Iterate with enumerate instead of range(len(x)).
  2. Use list comprehension rather than using raw for loops.
  3. Sort complex iterables with sorted() .
  4. Store unique values with Sets.
  5. Save memory with Generators.
  6. Define default values in Dictionary with .get() and .setdefault() .
  7. Count hashable objects collections.Counter .
  8. Format strings with f-strings.
  9. Concatenate strings with .join().
  10. Merge Dictionaries with {**d1, **d2} .
  11. 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)):
#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]

#using list comprehension
list = [value*value for index, value in enumerate(list)]

Sort complex iterables with sorted()

list = [10, 30, 20, 50, 40]
#sort in accending order
accending = sorted(list)

#sort in descending order
descending = sorted(list, reverse=True)

Store unique values with Set

list = [10, 30, 10, 20, 30, 20, 50, 50, 40, 30]
#find unique items only
unique_items = set(list)

Save memory with Generators

list = [i for i in range(10000)]

#using generator <-- does lazily so less memory
list = (i for i in range(10000))

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", 4))

#default value can be set using .setdefault() as well
dict.setdefault("five", 5)

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)

Format strings with f-strings

target = "World !"
str = f"Hello {target}"

Concatenate strings with .join()

str = ["Welcome", "to", "the", "club", "!"]
str = " ".join(str)

Merge dictionaries with {**d1, **d2}

dict1 = {"one": 1, "two": 2}
dict2 = {"three": 3, "four": 4}
merged = {**dict1, **dict2}

Simplify if statement with if x in [a, b, c]

item_color = "red"
if item_color == "black" or item_color == "red" or item_color == "green":
    print("color found !")
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.


You May Also Like