5 Python Tricks Every Python Developer should know
Tags: python, programming, tutorial, beginners
Published: 2023-01-03 17:33:29

Photo by <a href="https://unsplash.com/@cdr6934?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Chris Ried</a> on <a href="https://unsplash.com/photos/ieic5Tq8YMk?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>

---

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/webmlj68iufa370gjrw6.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b4ff2aebfbhtyy7d02rq.png)
Suppose you are interested in getting some specific variable in your sequence or iterable you can create [discards](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards) also called [throwaway](https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python) variables. Here is an example : 

![How to use underscores or throwaway variables in python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijzyzc2c2640d1ar1xgp.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rb4rhmzfxw989h8sr1s3.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lax9depato88d5sqo1qn.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qxepq8ot3vzppj0612ui.png)
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](https://www.w3schools.com/python/python_lambda.asp) function as a key argument in our `max()` or `min()` function :


![Finding the key that corresponds to a maximum value in a dictionary](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpk8wwa59wbdxm0q30sa.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tjdy98jupr536095bs4r.png)

---

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znwkpz94hso9m1siu1cp.png)  
We can filter out ages less than or equal to 20 years by performing the following : 

![Using Dictionary Comprehension to filter values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fn2ne1berm4b0rg5hmgo.png)

![Using Dictionary Comprehension to filter values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f598hhv913tu10t57vyg.png)

---

## 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](https://docs.python.org/3/library/itertools.html#itertools.compress) function from [itertools](https://docs.python.org/3/library/itertools.html) module. 

Let's first import our `compress` function :

![from itertools import compress](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29nk6egf24vrtjbjfpt4.png) 
The `compress` will take an iterable and then selectors or boolean array. 

```js
compress(data, selectors)
```
Let's get our data and selectors: 

![Boolean masking or indexing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idfuftxrp3flx2p821jd.png)
Our list comprehension returns `True` if the number is negative or `False` otherwise. 

```python
my_bool
[False, False, False, True, False, True, False, False, True, False]
```
Now let's perform our boolean indexing: 

![Boolean indexing using Compress](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7dg0a04pcgun7g2g3zx.png)
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](https://docs.python.org/3/library/collections.html#collections.Counter) function in the [collections](https://docs.python.org/3/library/collections.html)

Let's import our `Counter` function :

![from collections import Counter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cca0rfy0031ye58it6gl.png)

![Creating a list in python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ef399skd86q1he5b7q9.png)
The `Counter` takes in an iterable, in this case `my_list`. 

Creating a Counter object : 

![Creater a Counter in Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i74v8pmevatt7skpfkor.png)

Finding the two most common items in our list:

![Finding the mode of an element in Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yarbkk20os8vb8xzw1lv.png)
`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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agvbwfn15ydnl7ac5cta.png)

>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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ts3wki9zv2w5uk7h67fw.png)

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

![Updating Counter object in Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y8vhov5urx0hhbru9isb.png)

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

![Counter.update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57hdi205ddwptmghtg05.png)

Performing add and subtract operations on two Counter objects:

![Add or subtract two Counter Objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kya7wfyqxupa6su5edi.png)

--- 

## References 

- [Counter Documentation](https://docs.python.org/3/library/collections.html#collections.Counter)

- [collections Documentation](https://docs.python.org/3/library/collections.html)

- [Python Cookbook](https://www.oreilly.com/library/view/python-cookbook-3rd/9781449357337/)