Did you say "Pythonic"?
Tags: python, beginners, webdev
Published: 2023-03-24 17:56:21

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](https://hub.packtpub.com/write-python-code-or-pythonic-code/), 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:

```python
by_two = []
for x in range(1, 11):
by_two.append(x * 2)
```

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

```python
by_two = [x * 2 for x in range(1, 11)]
```

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:

```python
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
```

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:

```python
table = [[x * y for x in range(1, 11)] for y in range(1, 11)]
```

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:

```python
sentence = "This is a sentence with some repeated words"
words = {word.lower() for word in sentence.split()}
```

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:

```python
#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
```
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](https://peps.python.org/pep-0008/).

### 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](https://peps.python.org/pep-0020/).