7 Python Tricks And Tips You Must Know
Python is an incredibly versatile programming language, it has easy to understand syntax and mastering it takes significantly lesser effort than many other languages out there. Despite this ,even very experienced python developers do not know simple tips and tricks which can be really useful at times. Here's a list of neat tips and tricks which you must know.
1.Measure time taken for a part of code to get executed
Sometimes, your application may be running slow and it can be really difficult to know what part of the code is causing the issue, to solve this you can look at the time taken by certain parts of the code by using this code snippet 👇
import time startTime = time.time() # write your code or functions calls endTime = time.time() totalTime = endTime - startTime print("Time taken to execute code= ", totalTime)
2.View the memory taken by an Object
In Python you can use the
sys.getsizeof function to check the memory consumed by an object in python, like Lists, Tuples, Dictionaries etc.
Sometimes, it is good practice to check how much memory your data structure uses.
import sys list1 = ['Value1', 'Value2', 'Value3'] print("size of list = ",sys.getsizeof(list1))
3.Switch the values of 2 variables: The efficient way
🚫 Don't do this 👇
a = 10 b = 20 a = b b = c c = a print(a,b)
✅ Do this 👇
a = 10 b = 20 a,b=b,a print(a,b)
4.Remove duplicates from a list
This is a neat trick, here we convert the list to a set. Sets are unordered data-structures of unique values and don’t allow copies.
listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24] print("Original List= ", listNumbers) listNumbers = list(set(listNumbers)) print("After removing duplicate= ", listNumbers)
5.Combine 2 lists to form a dictionary
Here we use the
zip function to combine the 2 lists into a dictionary
price = [54, 65, 76] names = ["Pizza", "Pasta", "Burger"] convertedDictionary = dict(zip(price, names)) print(convertedDictionary)
6.Find the largest and smallest values from a list of numbers
For extracting the largest and smallest values from a list, we can use the
list = [1,2,3,4,5,6] smallest = min(list) print(smallest) largest = max(list) print(largest)
Let's say you want to make a list with even numbers from 0-20.
The typical approach would be:
A = [i for i in range(20)] B = [x for x in A if x%2 == 0] print (B)
The more efficient approach would be:
A = [x for x in range(20) if x%2 == 0] print(A)
I hope you found these tips and tricks useful.
You can find me on Twitter Here