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.
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 :
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 :
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.
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:
You might want to know the person who has the maximum/minimum age. Your guess will be to perform the following :
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 :
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 :
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.
We can filter out ages less than or equal to 20 years by performing the following :
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 :
The compress
will take an iterable and then selectors or boolean array.
compress(data, selectors)
Let's get our data and selectors:
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]
Now let's perform our boolean indexing:
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 :
The Counter
takes in an iterable, in this case my_list
.
Creating a Counter object :
Finding the two most common items in our list:
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:
Suppose we have a different list of words which has the same kind of items in our Counter we increase our counter as below:
Now let's check the count of some elements in our Counter:
We can achieve the same thing by using the update()
function :
Performing add and subtract operations on two Counter objects:
Top comments (11)
Wow these are some cools tricks ๐ฅ
Thanks!
Nice tricks, thanks.
Glad you love them!
that was perfect ๐
Thanks!
Hi Blessing Agyei Kyem,
Great article, thank you.
Following your example:
I tried this:
It does not like it:
While this is acceptable:
Take care.
You can't use
*
twice in your code when unpacking the elementsI 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.