Useful modern Python Tips & Tricks

Akshay Jain
3 min readMar 30, 2022

Here I have come up with new tips and tricks which I like the most and even they help me to code correctly in a fast and very efficient way.

1. Use of yield in Helper function

yield will definitely going to save time and even few lines of code.

Ok, Let me give you an example of function that returns squared numbers. Now here, the flow is like: 1. iterate through all numbers. 2. perform square of each number and append it to new variable 3. at last we need to return that list.

def square_numbers(numbers):
new_numbers = []
for number in numbers:
squared_number = number*number
new_numbers.append(squared_number)
return new_numbers

To get rid of this things let me show you an example with the help of yield keyword.

def square_numbers(numbers):
for number in numbers:
yield number*number

Wow! now our code looks pretty simple. Now let’s see how yield works.

As we know return keyword returns the value and stop the function. But, the yield keyword continuously returns the value but it doesn’t stop the function. With this yield our function become generator and it returns generator function.

result = square_numbers(range(1, 10))
print(result) # <generator object square_numbers at 0x7fa02dcc9360>
print(list(result)) # [1, 4, 9, 16, 25, 36, 49, 64, 81]

2. Chain comparison operators for condition check

In our coding life, there is a case where we need to compare values, very common like a < b and b < c. So let me give you a better way in python to make it simpler.

n1 = 1
n2 = 5
n3 = 10
number = (n1 < n2 and n2 <n3) # Common syntax-----or-----number = (n1 < n2 < n3) # pretty simple

So, The chaining of operators make our developers life easier.

3. Destructuring Assignments

Let me take a best example of using destructuring assignment. Let say if we want to swap two numbers then we make use of a third variable to swap the two numbers.

n1 = 5
n2 = 10
tmp = n1 # assign n1 to tmp
n1 = n2 # swap n2 value to n1
n2 = tmp # swap tmp (contains n1’s value) to n2

In python we can easily achieve this in one single line of code

n1 = 5
n2 = 10
n1, n2 = n2, n1

So this is how destructuring assignment works.

4. List comprehensions

In python, you can iterate through the items present in list in just single line of code.

numbers = [i for i in range(1, 10)]
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
----OR----numbers = []
for i in range(1, 10):
numbers.append(i)
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also use this comprehensive feature for dictionary, set as well.

5. Use of defaultdict in python

First lets talk about dictionary, it stores in key-value pair and key must be immutable and unique. But in dictionary their is one problem, when we try to access the key which is not present in dictionary, at that time it raise an KeyError error and sometimes it might become a problem.

So to overcome this problem, Python support other type of collection that is defaultdict that is present in the collections module. defaultdict never raise a KeyError and instead of error it returns the default value for the key which is not present in dictionary.

from collections import defaultdictitems = defaultdict(list) # declare statement
items["n1"] = 1
print(items["n1"]) # output: 1
print(items["n2"]) # output: [] -> here n2 key is not present

In above example you can see, we are trying to access the key n2 which is not present in dictionary items then also it not raise an error, instead it returns empty list.

That’s all, I hope these tips and tricks are helpful to you in your code. Thank you for your time.

--

--

Akshay Jain

Full-Stack Developer | Python | React JS | PostgreSQL