DEV Community

Cover image for 5 Python Tricks Every Python Developer should know
Blessing Agyei Kyem
Blessing Agyei Kyem

Posted on • Updated on

5 Python Tricks Every Python Developer should know

Photo by Chris Ried on Unsplash


As a Python developer or enthusiast, it's recommended you know some python tricks to help you facilitate your work as a programmer and reduce repetitive or boring tasks.

Below are the 5 important tricks you should know :


1. Sequence Unpacking

Sequence unpacking allows you to assign multiple elements of a sequence to variables. This is really helpful when you have a really large sequence of items and you want extract say the last 3 elements and store them in variables.

Unpacking a Sequence in Python
As illustrated above, x variable stores 'Come', y variable stores 'go', z variable stores 1.5 and finally the tup variable stores our tuple (1, 0, 1)

NOTE : The number of elements you are trying to unpack must match the number of variables or assignments.

One can also unpack the elements of a string :

Unpacking elements of a string
Suppose you are interested in getting some specific variable in your sequence or iterable you can create discards also called throwaway variables. Here is an example :

How to use underscores or throwaway variables in python

If you have more elements in your iterable than the number of elements you want to unpack or you want to unpack some elements into a list, you can attach an asterisk(*) in front of a variable to unpack multiple items at a time.
Unpacking elements with * in python
Python assigns the last element which is 10 to the last_num variable because that variable was written last. The remaining elements are assigned to the first_9 variable because it has * in front of it.

NOTE : Unpacking multiple elements with a variable having * in front of it will always return a list.


2. Performing Operations on Dictionaries

One can perform important operations such as finding the maximum/minimum values and sorting the values in a dictionary with ease.
Imagine you have a dictionary having keys to be some people's names and values as their ages:

Calculating with Dictionaries
You might want to know the person who has the maximum/minimum age. Your guess will be to perform the following :

Using zip() to find the maximum values in a dictionary
The implementation above returns a tuple which still doesn't solve our problem. We want to return only the key which corresponds to maximum/minimum age which in this case is Ama/Blessing.

We can solve this problem by using the lambda function as a key argument in our max() or min() function :

Finding the key that corresponds to a maximum value in a dictionary
The s is just an arbitrary variable that is used to represent any key in our ages dictionary.

We can also find the person with the minimum age by using the min function :

Finding the key that corresponds to a minimum value in a dictionary


3. Sub-setting a Dictionary

We can perform dictionary comprehension to filter our dictionary based on certain values. You might be interested in creating a new dictionary from an existing dictionary by filtering out say ages of people less than or equal to 20 years.

Dictionary comprehension

We can filter out ages less than or equal to 20 years by performing the following :

Using Dictionary Comprehension to filter values

Using Dictionary Comprehension to filter values


4. Perform Boolean Masking Without Using Numpy

Boolean masking also known as Boolean indexing is mostly implemented using python libraries like Numpy. We can achieve this by using compress function from itertools module.

Let's first import our compress function :

from itertools import compress
The compress will take an iterable and then selectors or boolean array.

compress(data, selectors)
Enter fullscreen mode Exit fullscreen mode

Let's get our data and selectors:

Boolean masking or indexing
Our list comprehension returns True if the number is negative or False otherwise.

my_bool
[False, False, False, True, False, True, False, False, True, False]
Enter fullscreen mode Exit fullscreen mode

Now let's perform our boolean indexing:

Boolean indexing using Compress
The data is compressed with our selectors and then the values in our data with corresponding True values are returned.

As you can see the negative values in my_list were -2, -7, -1 and they have all been returned.


5. Speeding up Counting Operations

We can perform operations such as finding the most frequent item in a list and other arithmetic operations by using Counter function in the collections

Let's import our Counter function :

from collections import Counter

Creating a list in python
The Counter takes in an iterable, in this case my_list.

Creating a Counter object :

Creater a Counter in Python

Finding the two most common items in our list:

Finding the mode of an element in Python
most_common() function returns a list of tuples. For every tuple, the first element indicates the element and the second element indicates the number of times that particular element appeared in our list. The function takes in an optional argument which indicates the number of most common elements you want to return. This is useful if you want to find the mode of a dataset or create a frequency table.

In our case, the most frequent element is 4(appeared 5 times) followed by 2(appeared 4 times).

Counter is like a dictionary that maps the items to the number of occurrences.
We can access the number of occurrences of the elements as follows:

Finding the number of occurrences using Counter function

Suppose we have a different list of words which has the same kind of items in our Counter we increase our counter as below:

Updating our Counter object with some elements

Now let's check the count of some elements in our Counter:

Updating Counter object in Python

We can achieve the same thing by using the update() function :

Counter.update

Performing add and subtract operations on two Counter objects:

Add or subtract two Counter Objects


References

Top comments (11)

Collapse
 
samadon1 profile image
Samuel Amankwah Donkor

Wow these are some cools tricks ๐Ÿ”ฅ

Collapse
 
blessing988 profile image
Blessing Agyei Kyem

Thanks!

Collapse
 
ilteriskeskin profile image
Ali ฤฐlteriลŸ Keskin

Nice tricks, thanks.

Collapse
 
blessing988 profile image
Blessing Agyei Kyem

Glad you love them!

Collapse
 
mohammadparsajavidi profile image
mohammadparsa-javidi

that was perfect ๐Ÿ‘Œ

Collapse
 
blessing988 profile image
Blessing Agyei Kyem

Thanks!

Collapse
 
behainguyen profile image
Be Hai Nguyen

Hi Blessing Agyei Kyem,

Great article, thank you.

Following your example:

ten_numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

*first_9, last_num = ten_numbers
Enter fullscreen mode Exit fullscreen mode

I tried this:

*first_2, *next_7, last_num = ten_numbers

print(first_2)
print(next_7)
print(last_num)
Enter fullscreen mode Exit fullscreen mode

It does not like it:

SyntaxError: multiple starred expressions in assignment
Enter fullscreen mode Exit fullscreen mode

While this is acceptable:

_, _, *three_to_nine, last_num = ten_numbers

print(three_to_nine)
print(last_num)
Enter fullscreen mode Exit fullscreen mode
[3, 4, 5, 6, 7, 8, 9]
10
Enter fullscreen mode Exit fullscreen mode

Take care.

Collapse
 
blessing988 profile image
Blessing Agyei Kyem

You can't use * twice in your code when unpacking the elements

Collapse
 
behainguyen profile image
Be Hai Nguyen

I used this before. But not with *. Thank you and take care.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.