5 Python Tricks Every Python Developer should know

blessing988

Blessing Agyei Kyem

Posted on January 3, 2023

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

💖 💪 🙅 🚩
blessing988
Blessing Agyei Kyem

Posted on January 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related