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: 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 -
for i in range(len(arr)):
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 -
for i, j in enumerate(arr):
Well, now it looks better and more Pythonic. What about converting a list into a string?
# The C way
string = ''
for i in arr:
string += i# The Python way
string = ''.join(arr)
join, Python has a plethora of magical keywords, so don’t work for the language, make the language work for you.
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 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
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.”
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 -
for ind, val in enumerate(arr):
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-
# 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 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.
yield or not to
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
Ever heard of itertools?
A faster, more memory-efficient way to perform iterator algebra. From
product, this module 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-
from itertools import combinationsnames = 'ABC'
for combination in combinations(names, 2):
print(combination)''' Output -
May I introduce you to Python’s collections?
The collections module provides alternatives to built-in data types like
tuple, etc. They have various containers like
deque, etc that work really efficiently for some problems. Allow me to demonstrate -
# frequency of all characters in a string in sorted orderfrom collections import (OrderedDict, Counter)string = 'abcbcaaba'
freq = Counter(string)
freq_sorted = OrderedDict(freq.most_common())for key, val in freq_sorted.items():
print(key, val)''' Output -
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.
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 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 -
# bad code
if num >= 0:
return False# good code
return num >= 0# while comparing None
# 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 there were my two cents on the most basic ones. DM me on Twitter if you agree with me, disagree, or just want to wish me a good day. Congratulations! You are now a Pythonista.