How To Write Better Python Code?
Tags: python, beginners, 100daysofcode, productivity
Published: 2020-05-19 20:17:15

![Python Meme](https://dev-to-uploads.s3.amazonaws.com/i/oy06h5rg0asj32qoyaxp.jpg)
We all love Python. It’s easy to write and understand but that doesn’t give us the right to abuse a wonderful language by ignoring the rules and writing code in a non-Pythonic way. Consider this article as the [Zen of Python](https://www.python.org/dev/peps/pep-0020/): Extended. Here are 10 ways to write better code in Python:

Are you writing C code?
=======================

If you were asked to print all the elements in a list along with their indexes and the first thing that came to your mind was this -

```python
for i in range(len(arr)):  
    print(i, arr[i])
```

Then you, my friend, are still writing C code. Allow me to introduce you to `enumerate`. It indexes all the elements in your list/string and your code becomes -
```python
for i, j in enumerate(arr):  
    print(i, j)
```
Well, now it looks better and more Pythonic. What about converting a list into a string?

```python
# The C way  
string = ''  
for i in arr:  
    string += i

# The Python way  
string = ''.join(arr)
```

Just like `join`, Python has a plethora of magical keywords, so don’t work for the language, make the language work for you.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1to9uwdybq35pfgbt7rq.png)

Remember PEP8?
==============

It’s like the rulebook you probably throw away because you are one of the cool kids. I’m not asking you to religiously follow it, all I’m asking for is to follow most of it because our founding father said that “Code is read much more often than it is written,” and he was dang right.

Do you ever look at your code and wonder? What the heck does that do? Why is it there? Why do I exist? Well, [PEP8](https://www.python.org/dev/peps/pep-0008/) is the answer to most of these questions. While comments are a good way of explaining your code, you still need to change the code and if you can’t remember what `i`, `j`, `count`, etc stand for, you’re wasting your valuable time as well as of the poor human that’ll have to read and change your code.

> “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1732ewtskhe0vxao1sfn.jpg)

Prefer **CamelCase** for classes, **UPPER_WITH_UNDERSCORES** for constants, and **lower_with_underscores** for variables, methods, and module names. Avoid single name functions, even when using `lambda`. In the spirit of that, let’s change our previous code to -

```python
for ind, val in enumerate(arr):  
    print(ind, val)
```

Are list comprehensions your best friend?
=========================================

If you don’t know about it yet or aren't convinced why you should use it, let me give you an example-

```python
# bad code  
positives = []  
for val in arr:  
    if val >= 0:  
        positives.append(val)

# good code  
positives = [val for val in arr if val >= 0]
```

You can use this for dictionaries and sets. It’s even perfect for playing code golf while being readable.

Still explicitly closing files?
===============================

If you are a forgetful person like I am, Python has your back. Instead of explicitly opening your file and then typing `filename.close()` every time, simply use `with` -

```python
with open('filename.txt', 'w') as filename:  
    filename.write('Hello')
# when you come out of the 'with' block, the file is closed
```

Iterators or generators?
========================

Both iterators and generators are powerful tools in Python that are worth mastering. An iterator returns an iterator object, one value at a time whereas generators yield a sequence of values while being memory efficient as they do not store the entire range of values, rather generate one only when you ask for it, unlike iterators that return the entire range of values. This makes generators extremely fast, compact, and simple.

To `yield` or not to `yield`?
=============================

When using generators, blindly use `yield`. It will freeze the state of the generator and resume again from where you left off, should you require another value. But don’t use it, just for the sake of not using `return`. Both have their place and it is neither fancy to use `yield` nor ordinary to use `return`.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/j5cexmjxhxo5y2xkhico.jpg)

Ever heard of itertools?
========================

A faster, more memory-efficient way to perform iterator algebra. From `count` and `cycle` to `groupby` and `product`, this [module](https://docs.python.org/3/library/itertools.html) has some amazing tools to make your life easier. If you want all the combinations of characters in a string or of numbers in a list you can simply write-

```python
from itertools import combinations
names = 'ABC'  
for combination in combinations(names, 2):  
    print(combination)
''' Output -  
    ('A', 'B')  
    ('A', 'C')  
    ('B', 'C')  
'''
```

May I introduce you to Python’s collections?
============================================

The [collections](https://docs.python.org/3/library/collections.html) module provides alternatives to built-in data types like `dict`, `tuple`, etc. They have various containers like `defaultdict`, `OrderedDict`, `namedtuple`, `Counter`, `deque`, etc that work really efficiently for some problems. Allow me to demonstrate -

```python
# frequency of all characters in a string in sorted order
from collections import (OrderedDict, Counter)
string = 'abcbcaaba'  
freq = Counter(string)  
freq_sorted = OrderedDict(freq.most_common())
for key, val in freq_sorted.items():  
    print(key, oval)
''' Output -  
    ('a', 4)  
    ('b', 3)  
    ('c', 2)  
'''
```

Is OOP your religion?
=====================

Don’t overuse classes. Hang on Java and C++ peeps who are out there to get me. You can keep all your fancy classes and functions that are slaves to objects (yes Java, I’m looking at you), but when using Python you can just re-use code with the help of functions and modules. You don’t have to create classes when there is absolutely zilch need for it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x2jwk9m9s8kx8agthgx2.jpg)

Docs or Tutorials?
==================

You have truly progressed as a programmer when you prefer docs over tutorials or StackOverflow. I absolutely do not mean that documentation is the better being and tutorials shouldn't exist, however, once you are comfortable with a language, read docs more often, especially for something so beautiful like [Python](https://docs.python.org/3/) where everything is so perfectly explained that you could read it like a story-book. You will find interesting things to play around with and even if you don’t use them, it will be a fun ice-breaker at an all-coders party :p

* * *

Bonus code snippets for the lucky people who stayed till the end -

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u53o0r1lzij0its6q7p2.jpg)

```python
# bad code  
def is_positive(num):  
    if num >= 0:  
        return True  
    else:  
        return False
# good code  
def is_positive(num):  
    return num >= 0

# bad code  
if value == None:  
    # some task
# good code  
if value is None:  
    # some task

# unpacking a list into a variable and another list  
roll, *marks = roll_and_marks
```

* * *

There are numerous other ways in which we can write more Pythonic code but these were my two cents on the most basic ones. Comment down below if you agree with me, disagree, or just want to wish me a good day. You can also reach out to me on [Twitter](https://twitter.com/iiverveii). Congratulations! You are now a Pythonista.