Did you say "Pythonic"?

gabygalv

gabygalv

Posted on March 24, 2023

Did you say "Pythonic"?

Python is a popular and versatile programming language that has many features and benefits. But not all Python code is created equal. Some code follows the best practices and conventions of the Python community, while some code just gets the job done.

I'll be explaining what pythonic code is and a few ways to make your code more "pythonic".

What Does Pythonic Mean?

According to Packt Hub, Pythonic means:

When people talk about pythonic code, they mean that the code uses Python idioms well, that it’s natural or displays fluency in the language. In other words, it means the most widely adopted idioms that are adopted by the Python community.

Pythonic code is code that follows the principles and philosophy of Python, such as simplicity, readability, elegance, and expressiveness. It can also be described as code that makes the best use of the language features and the standard library.

It's not just about syntax or style, but also about logic and design. Pythonic code avoids common pitfalls and anti-patterns, such as unnecessary complexity, repetition, or "hack-y" work arounds.

How to Write Pythonic Code

Writing Pythonic code is not something that you can learn overnight. It requires practice and familiarity with the language and its idioms. Luckily, there are some general tips and guidelines that can help you improve your Python skills and write more Pythonic code.

Here are some of them:

Use List Comprehensions

List comprehensions are one of the most distinctive and powerful features of Python. They allow you to create new lists from existing iterables (lists, tuples, sets, dictionaries, etc.) in a concise way.

For example, if you want to create a list of multiples of 2 for the numbers from 1 to 10. You could do it with a for loop like this:

by_two = []
for x in range(1, 11):
by_two.append(x * 2)
Enter fullscreen mode Exit fullscreen mode

This works, but a more Pythonic way to do it is with a list comprehension like this:

by_two = [x * 2 for x in range(1, 11)]
Enter fullscreen mode Exit fullscreen mode

This is much shorter and clearer than the for loop version. It also avoids the inefficiency of creating an empty list and appending to it.

List comprehensions can also have conditions to filter out unwanted elements. For example, if you wanted to create a list of even squares from 1 to 10. You could do it with a list comprehension like this:

even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode

This will only include the squares of even numbers in the new list.

List comprehensions can also be nested to create lists of lists or other complex structures. If you want to create a list of lists that represents a multiplication table from 1 to 10. You could do it with a nested list comprehension like this:

table = [[x * y for x in range(1, 11)] for y in range(1, 11)]
Enter fullscreen mode Exit fullscreen mode

This will create a list of 10 lists, each with 10 elements that are the products of two numbers from 1 to 10.

You can also use list comprehension for other types of collections such as sets or dictionaries. If you wanted to create a set of unique words from a sentence. You could do it with a set comprehension like this:

sentence = "This is a sentence with some repeated words"
words = {word.lower() for word in sentence.split()}
Enter fullscreen mode Exit fullscreen mode

This will create a set of lowercase words from the sentence without any duplicates.

Use built-in data structures and functions

Python has a set of built-in data structures and functions that can help you solve many common problems. You can use lists, tuples, dictionaries, sets, strings, numbers, booleans, etc. to store and manipulate data. You can also use functions like len, max, min, sum, sorted, map, filter, zip, etc. to perform operations on data.

Using built-in data structures and functions can make your code more concise, efficient and readable (some might even say.. pythonic?). Instead of writing a loop to iterate over a list and check if an element is in another list, you can use the in operator:

#bad
def check_element(element, list1, list2):
for x in list1:
if x == element:
if element in list2:
return True
return False

#good 
def check_element(element, list1, list2):
return element in list1 and element in list2
Enter fullscreen mode Exit fullscreen mode

Don't we just love turning a 6 line loop into a single line? chefs kiss

Use meaningful names and consistent style

One of the most important aspects of writing readable and maintainable code is using meaningful names for your variables, functions, classes and modules. Meaningful names can help you and others understand what your code does and why. They can also help you avoid errors or bugs by making your code more self-documenting.

You should also follow a consistent style for your naming conventions. For example, you should use lowercase letters with underscores for variables and functions (my_variable, my_function), AKA snake case.

Python has quite an extensive style guide which can be found here.

Are you feeling Pythonic?

Well, now that we've all read the word pythonic 15 times and covered a few ways to improve our code we know that it's not just about following some rules or conventions, writing pythonic code is a philosophy. I'll leave you with a few of my favorite thoughts from the Zen of Python:

Beautiful is better than ugly.
Simple is better than complex.
Complex is better than complicated.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
If the implementation is hard to explain, it's a bad idea.

You can access the full Zen of Python guidelines by typing import this in your interpreter or going here.

💖 💪 🙅 🚩
gabygalv
gabygalv

Posted on March 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related