9 Tricks to Follow Best Practices in Python

Ever wondered if there is a more efficient way of writing a block of weird looking code? Check out these tricks, you will find out.

Juan Velasquez
3 min readSep 4, 2021
  • Use enumerate() instead of range(len()) :

While iterating over a list, is very common to logically come up with range(len()) , but enumerate() gives you access not only to the index but also the value directly.

  • Use list comprehension and avoid classic for loops:

List comprehensions is a very powerful tool and you should implement it when you are populating a list or in general, working with iterables. Here is an example comparing both methods.

  • Use generators instead of list comprehension to save memory:

Similarly to list comprehensions you can implement generators. A generator computes its elements lazily (just when demanded) so it uses only one item at a time. Below you can see that both give the same result but the size of the generator is significantly lower. This can make a great difference when working with large data.

  • Sort iterables with sorted() :

If you need to sort some iterable, you don’t need to implement the sorting algorithm, there is already a built-in function that does it for you. Let’s see an example with a tuple and a dictionary. Note: sorted() returns a list.

  • Store unique values using sets:

A set is an unordered collection of data that is iterable, mutable and has no duplicate elements. It can be very useful when you have a list and want to get rid of duplicates.

This feature is available since Python 3.6, and it’s definitely the best way to write a string that include variables and even some expressions. If you want to find more about f-strings I wrote an article talking about all its functionalities (article).

  • Use join() to concatenate strings in a list:

Very often you will have a list that you want to convert into a string. This can be of course implemented by yourself, but in most cases using join() will be more efficient, clean and simple.

  • Merge dictionaries:

Since Python 3.5 you can merge dictionaries using the unpacking syntax {**dict_1, **dict_2}. It will update the values of keys already existing and create the new ones.

  • Use wisely your if-statements:

Simplify your if-statements. When you have a variable and want to check if it’s part of values, sometimes is easy to follow logic and write statements that are quite verbose and error prone. A very simple way of dealing with this is creating a list containing the values that you want to compare with and use the in keyword.

Overview:

So this is what we learned in this article:

  • Use enumerate() instead of range(len()).
  • Use list comprehension and avoid classic for loops.
  • Use generators instead of list comprehension to save memory.
  • Sort iterables with sorted().
  • Store unique values using sets.
  • Format strings using f-strings.
  • Use join() to concatenate strings in a list.
  • Merge dictionaries.
  • Use wisely your if-statements.

I hope you enjoyed this content, if you have any questions or ideas just leave them in the comments.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
— Martin Fowler

--

--

Juan Velasquez
Juan Velasquez

Written by Juan Velasquez

Software developer. Python. Automation tester. Microelectronics. Twitter: @__jvelasquez__

No responses yet