I thought I had mastered Python — until I discovered these tricks

Python best practices and tips that will make you code quickly and efficiently

9. List Comprehension

The traditional way with for and if:

Using a list comprehension:

The listcomps are clear and direct. You can have severalfor loopsandif conditionswithin the same listcomp, but beyond two or three, or if the conditions are complex, I suggest you use the usualfor loop.

For example, the list of squares from 0 to 9:

The list of odd numbers within the previous list:

Another example:

1. Readability is important

First of all, try to make your programs easy to read by following some programming conventions. A programming convention is one that a seasoned programmer follows when writing his or her code. There’s no quicker way to reveal that you’re a“newbie”than by ignoring conventions. Some of these conventions are specific to Python; others are used by computer programmers in all languages.

Essentially, readability is the characteristic which specifies how easy another person can understand some parts of your code (and not you!).

As an example, I was not used to write with vertical alignment and to align the function’s parameters with opening delimiter.

Look at other examples in theStyle Guide for Python Codeand decide what looks best.

Another important thing that we do very often is resembling programs that we have seen or written before, which is why our exposure to readable programs is important in learning programming.

2. Avoid unuseful conditions

Often, a longif & elif & …. & elseconditions is the sign of code that needs refactoring, these conditions make your code lengthy and really hard to interpret. Sometimes they can easily be replaced, for example, I used to do the following:

This is just dumb! The function is returning a boolean, so why even use if blocks in the first place? The correct what of doing this would be:

In aHackerrankchallenge, you are given the year and you have to write a function to check if the year is leap or not. In the Gregorian calendar three criteria must be taken into account to identify leap years:

So in this challenge, forget aboutifsandelsesand just do the following:

3. Adequate use of Whitespace