The world’s leading publication for data science, AI, and ML professionals.

7 Amazing Python Tricks That You Must Know

Easier yet useful tips for python programmers

Credit: Pexels
Credit: Pexels

We all know that Python codes are more concise and have higher reliability than other languages. But Python is more powerful than you think. There are numerous shortcuts and tricks to use in Python which will definitely make the codebase much more precise and will optimize the execution of the code too.

In today’s article, we will talk about 7 such tips and tricks which you can readily use in your Python project. Most of the tricks are not always used by a beginner programmer so it will also help you to stand out from the rest!


1. Calculate the runtime of your code

Calculating the run time of your code becomes important if you are comparing different sets of code for the most optimized solution e.g. selecting the fastest algorithm for your problem.

This small trick will definitely help you in achieving that. Here we will take the help of the time module that comes with python

import time
startTime = time.time()
#Our main code starts here
x = 10
y = 20
z = x+y
print(f"the sum is: ",z)
#Our main code ends here
endTime = time.time()
net = endTime - startTime
print(f"time taken: ",net)

Output

the sum is: 30
time taken: 0.0008382797241210938

2. Typecasting a whole list

Sometimes we need to change the datatype of all the items in a list. The normal meet on this is to do that using a loop. But this method is not optimized at all and we can make the process much faster and straightforward using the map function in python.

list1 = [1,2,3,4,5]
print(f"list in integer form: ", list1)
list2 = list(map(float,list1))
print(f"list in float form: ", list2)

Output

list in integer form: [1, 2, 3, 4, 5]
list in float form: [1.0, 2.0, 3.0, 4.0, 5.0]

3. Find the transpose of a matrix

Sometimes we need to find the transpose of a matrix while working with problems related to Data Science.

Although there is a separate method in NumPy to get the transpose of a matrix, we can do that using simple Python also using the zip() function.

matrix = [[1, 2, 3], [4, 5, 6]]
transpose =zip(*matrix)
for row in transpose:
print(row)

Output

(1, 4)
(2, 5)
(3, 6)

4. Inverting a dictionary

Let’s say you face a condition where you have to invert a dictionary i.e. the keys in the previous dictionary will be the values for the current dictionary and vice versa.

You can do that using a for loop with just one line of Python. But here you cannot make the changes in the same dictionary. You have to create a new dictionary for storing the key-value pairs.

dict1={"key1": 1, "key2": 2, "key3": 3, "key4": 4}
dict2={v: k for k, v in dict1.items()}
print(dict2)

Output

{1: 'key1', 2: 'key2', 3: 'key3', 4: 'key4'}

5. Counting the occurrence of a word in sentences:

If you want to find the number of times a particular word appears in a group of sentences, the most common method is to split the words in a sentence into a list and then check for the specific word in the list.

But the re module in Python makes it much easier with the findall() method. And this method works perfectly even if there are multiple sentences.

import re
sentence = "I have 3 cats, my friend has 3 cats. In total we have 6 cats"
len(re.findall('cats', sentence))

Output

3

6. Enumerate function

If you want to keep a crack of the list item’s indices along with the list items in a list, you can use the enumerate() function present in Python. This function can be especially helpful while working with algorithmic problems.

names = ["Ram","Shyam","Vivek","Samay"]
for index, element in enumerate(names):
print("Name at Index", index, "is", element)

Output

Name at Index 0 is Ram
Name at Index 1 is Shyam
Name at Index 2 is Vivek
Name at Index 3 is Samay

7. Merging two lists to form a dictionary

Let’s say you have a list of items and a list of their prices and you want to store them as a dictionary where the key:value will be items:price.

The general method is to use a for loop to traverse through both the list and combine them in a dictionary. But with the help of the zip function in Python, you can do that with one line of code.

items = ["jackets", "shirts", "shoes"]
price = [100, 40, 80]
dictionary = dict(zip(items, price))
print(dictionary)

Output

{'jackets': 100, 'shirts': 40, 'shoes': 80}

Conclusion

These were a few Tips and tricks which you can implement in your code to improve the code quality and optimization. These tricks will also help you to decrease the lines of code.

For a better understanding, you can add comments to describe what the snippet does as most of these codes are too compact to be understood by a beginner. We will try to cover more Python tricks in our next articles.


Before you go…

If you liked this article and want to stay tuned with my upcoming exciting articles on Python & Data Science – do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership.

In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science.

Also, feel free to subscribe to my free newsletter: Pranjal’s Newsletter.


Related Articles