Python Programming

How to Write Pythonic Code

Ten examples of pythonic code style that will make your life easier as a python programmer

Erfandi Maula Yusnu, Lalu

--

Photo by Chris Ried on Unsplash

Pythonic code style is saved my time and make my profession as machine learning engineer and web developer easier to live. Before I knew how to write pythonic code, my code is mess and more like Java-style than python itself. I still can't move on from Java-style code, java really influences my style code in every programming language. But after I knew how to write an elegant python code or pythonic code, everything looks cleaner, easier to read, and lots of things start to shine.

My background in programming starts with learning pascal in my senior high school. After learning pascal in senior high school, again I meet with pascal at my university. But my curiosity programming language makes me start to learn another programming language like in C/C++, Java and PHP.

One of the programming languages that really influences me is Java programming language. Its really opens my mind to Object-Oriented Programming that makes my life easier to develop software for my thesis in the bachelor degree in information technology.

When I first learn python intensively, the way I write variable, function, method are unconsciously from java style code. So let me show you how pythonic code are alike and unpythonic code are alike.

Soo, Let's begin.

Example 1 Variable Declaration

notPythonicVarName = "hai this is string"pythonic_var_name = "hai this is string, with pythonic code"
a, b = 0, 1
d, e = "data", 100
f = "single variable"
name:str = "variable with type, only work with python 3"

Example 2 Looping Through The List

# Bad Code (Not Pythonic Code)
data = ["one", "two", "three"]
for i in range(0, len(data)):
print(data[i])
# Pythonic Code
data = ["one", "two", "three"]
for val in data:
print(val)
# output from both code
# one
# two
# three

Example 3 Looping Through The List with Index

# Bad Code (Not Pythonic Code)
data = ["one", "two", "three"]
for i in range(len(data)):
print(f'{i}:{data[i]}')
# Pythonic Code
data = ["one", "two", "three"]
for idx, val in enumerate(data):
print(f'{idx}:{val}')
# output from both code
# 0:one
# 1:two
# 2:three

Example 4 Looping The Lists Backwards

# Bad Code (Not Pythonic Code)
colors = ["red", "green", "blue", "black", "white"]
for idx in range(len(colors)-1, -1, -1):
print(f"{colors[idx]}")
# Pythonic Code
colors = ["red", "green", "blue", "black", "white"]
for color in reversed(colors):
print(f"{color}")
# output from both code
# white
# black
# blue
# green
# red

Example 5 Looping Over Two Collections

names = ["fandi", "hasan", "umar"]
colors = ["red", "green", "blue", "black", "white"]
# Bad Code (Not Pythonic Code)
n = min(len(names), len(colors))
for idx in range(n):
print(f'{names[idx]} --- {colors[idx]}')
# Pythonic Code
for name, color in zip(names, colors):
print(f'{name} --- {color}')
# output from both code
# fandi --- red
# hasan --- green
# umar --- blue

Example 6 Creating a List of Number

# Not Soo Good (Not so Pythonic Code)
list_number = []
for i in range(10):
list_number.append(i)
print(list_number)
# Pythonic Code
# List Comprehension
list_number = [idx for idx in range(10)]
print(list_number)
# output from both code
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 7 Looping Over Dictionary

dc = {"umar": "red", "hasan":"green", "fandi":"blue"}# Good Pythonic
for key in dc:
print(f'{key} --- {dc[key]}')
# More Pythonic
for key, val in dc.items():
print(f'{key} --- {val}')
# output from both
# umar --- red
# hasan --- green
# fandi --- blue

Example 7 Construct a Dictionary From Pairs

names = ["fandi", "hasan", "umar"]
colors = ["red", "green", "blue"]
# Not So Pythonic
d = {}
for name, color in zip(names, colors):
d[name] = color
# More Pythonic Code
d = dict(zip(names, colors))
# output from both code
# {'fandi': 'red', 'hasan': 'green', 'umar': 'blue'}

Example 8 Count with a Dictionary

colors = ["red", "green", "blue", "green", "red", "green"]# Not Soo Pythonic Code
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1
# Pythonic Code
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1
# Another Pythonic Code
from
collections import defaultdict
d = defaultdict(int)
for color in colors:
d[color] += 1

# code output

# {'red': 2, 'green': 3, 'blue': 1}

Example 9 Function Declaration

# Bad Code (Not Pythonic Code)
def addNumber(a, b):
return a + b
print(addNumber(10,5))# Pythonic Code
def add_number(a, b):
return a + b
print(add_number(10,5))# output from both code
# 15

Example 10 Class and Method Declaration

#Not Pythonic Class Method
class BadClass:
def sumAllNumber(self, list_number):
return sum(list_number)
obj = BadClass()
out = obj.sumAllNumber([5,5,2])
print(out)
# Pythonic Class Method
class PythonicClass:
def sum_numbers(self, numbers):
return sum(numbers)
obj = PythonicClass()
out = obj.sum_numbers([2,5,5])
print(out)
# output from both code
# 12

How to differentiate a pythonic code?

The soul of python code style has been carved in the zen of python. You can get the zen of python from python by writing import this in your python console. You can see it in detail in this picture below.

Image from Author

The example that you saw in this article comes from many resources, one of them is from Raymond Hettinger talk in youtube. I follow Raymond Hettinger videos several times in youtube, he opens up my mind to write python code to be more pythonic, simple and elegant.

This old man is my favourite man in python, one of the sentences that I highlighted from Raymond Hettinger videos if I’m not wrong,

the good python code is like business logic

I strongly recommend you to watch his lecture in python, the mindset of python programmer is different from other programmers. Soo, to shape your mind and to make your code faster, more readable, easier to manage and maintain I suggest you to watch and follow Raymond Hettinger in Youtube and Twitter.

Okay, I hope this article will be useful for a newcomer in python programming language, see you next time in another article.

--

--

Erfandi Maula Yusnu, Lalu

Remote Worker · Deep Learning Engineer · Web Developer · Teacher · Course Trainer · Archery Coach · Psychology Student · LinkedIn http://bit.ly/lDnUnE