Improve your Python with our efficient tips and tricks.
You can Practice tricks using Online Code Editor
Tip and Trick 1: How to measure the time elapsed to execute your code in Python
Let’s say you want to calculate the time taken to complete the execution of your code. Using a time module, You can calculate the time taken to execute your code.
Tip and Trick 2: Get the difference between the two Lists
Let’s say you have the following two lists.
list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
list2 = ['Scott', 'Eric', 'Kelly']Code language: Python (python)
If you want to create a third list from the first list which isn’t present in the second list. So you want output like this list3 = [ 'Emma', 'Smith]
Let see the best way to do this without looping and checking. To get all the differences you have to use the set’s symmetric_difference operation.
Tip and Trick 3: Calculate memory is being used by an object in Python
whenever you use any data structure(such as a list or dictionary or any object) to store values or records.
It is good practice to check how much memory your data structure uses.
Use the sys.getsizeof function defined in the sys module to get the memory used by built-in objects. sys.getsizeof(object[, default]) return the size of an object in bytes.
Output:
('size of list = ', 112)
('size of name = ', 49)
Note: The sys.getsizeof doesn’t return the correct value for third-party objects or user defines objects.
Tip and Trick 4: Removing duplicates items from a list
Most of the time we wanted to remove or find the duplicate item from the list. Let see how to delete duplicate from a list. The best approach is to convert a list into a set. Sets are unordered data-structure of unique values and don’t allow copies.
Output:
'Original= ', [20, 22, 24, 26, 28, 28, 20, 30, 24] 'After removing duplicate= ', [20, 22, 24, 26, 28, 30]
Tip and Trick 5: Find if all elements in a list are identical
Count the occurrence of a first element. If it is the same as the length of a list then it is clear that all elements are the same.
Output:
'All element are duplicate in listOne', True 'All element are duplicate in listTwo', False
Tip and Trick 6: How to efficiently compare two unordered lists
Let say you have two lists that contain the same elements but elements order is different in both the list. For example,
one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]Code language: Python (python)
The above two lists contains the same element only their order is different. Let see how we can find two lists are identical.
- We can use
collections.Countermethod if our object is hashable. - We can use
sorted()if objects are orderable.
Output:
'is two list areb equal', True
Tip and Trick 7: How to check if all elements in a list are unique
Let say you want to check if the list contains all unique elements or not.
Output:
All List elemtnts are Unique True All List elemtnts are Unique False
Tip and Trick 8: Convert Byte to String
To convert the byte to string we can decode the bytes object to produce a string. You can decode in the charset you want.
Output:
Byte to string is pynative
Tip and Trick 8: Use enumerate
Use enumerate() function when you want to access the list element and also want to keep track of the list items’ indices.
Output:
Using enumerate Index [ 0 ] Value 123 Index [ 1 ] Value 345 Index [ 2 ] Value 456 Index [ 3 ] Value 23
Tip and Trick 9: Merge two dictionaries in a single expression
For example, let say you have the following two dictionaries.
currentEmployee = {1: 'Scott', 2: "Eric", 3:"Kelly"}
formerEmployee = {2: 'Eric', 4: "Emma"}Code language: Python (python)
And you want these two dictionaries merged. Let see how to do this.
In Python 3.5 and above:
In Python 2, or 3.4 and lower
Tip and Trick 10: Convert two lists into a dictionary
Let say you have two lists, and one list contains keys and the second contains values. Let see how can we convert those two lists into a single dictionary. Using the zip function, we can do this.
Tip and Trick 11: Convert hex string, String to int
Tip and Trick 12: Format a decimal to always show 2 decimal places
Let say you want to display any float number with 2 decimal places. For example 73.4 as 73.40 and 288.5400 as 88.54.
Tip and Trick 13: Return multiple values from a function
Tip and Trick 14: The efficient way to check if a value exists in a NumPy array
This solution is handy when you have a sizeable NumPy array.

Hi Vishal!
Thank you so much for this website. I’m a beginner. I find out it’s easier than other sources. By the way, in the TRICK 2: If you want to create a third list from the first list which isn’t present in the second list. So you want output like this list3 = [ ‘Emma’, ‘Smith], I think we should use “difference(). Please re-check. Thanks!
Sir i have two coding challenges would like to share with you, so you can provide your solutions in PYTHON
I am so glad I found this wonderful site
And I need help
I make an invoice
the product . Unit price . Quantity . Total
If the invoice contains more than one product, only the first product is sent to the database
Example
The customer’s bill has a screen, a mobile phone, and a watch
Only the first line is sent
thank you
You’re thinking that, we don’t to write in a shorter way.
if we write in this way means beginners will also understand
……………………Totally unnecessary !!!!
even shorter ………………………….
from time import time
print(“Total time required to execute code is= “, time() – time())
😛
Lmao man. More power to this comment.
What’s this one measuring?
Hi,
Why the below code is not working in Python 2.7 version?
Python 2.7 command line
Got invalid syntax error on line
allEmployee = {**currentEmployee, **formerEmployee}Python 3 command line ouput
{1: 'Scott', 2: 'Eric', 3: 'Kelly', 4: 'Emma'}something
Change
print(allEmployee)
to
print allEmployee
What is the meaning of this code :
def num_66(n): for i in range(0, len(n)-1): if n[i:i+2] == [6,6]: return True return Falsehello!!! it says that
i in range(0, len(n)-1)if theiandi+1==6then the boolean value should be true if not it should be falseReturns true if 2 numbers in an array are both sixes and side by side.
Variable
goes through numbers in the range of 0 to the number of items in the list minus one.
What’s coming up in the
statement is called “slice”. That looks like this:
the ending index is exclusive, that just means it’s not included in the evaluation. That’s why they used
to get the neighbor of i instead of
.
If the sliced section of the list is equal to
], it evaluates to
and then returns
. If it never evaluates to
, it returns
.
Lol, didn’t know how code formatting worked on this site. My answer is still understandable but weird now.
Tip and Trick 5: Find if all elements in a list are identical
if you list is something like that:
pythonlistOne = [20, 555, 20, 20, ..., 20] # 1 million 20's inside this list print("All element are duplicate in listOne", listOne.count(listOne[0]) == len(listOne))Wouldn’t your code spend too many CPU’s cycles counting 20’s all over the list, when clearly that 255 already could indicate that the list doesn’t have identical items?
It may work for small lists, but for larger ones, I’d recommend creating a small function with a different approach (looping manually over the list and checking each value… and quitting as soon you see a difference)
Sorry, I thought I could format thas block as python code using markdown syntax. Too bad we can’t see a preview for our comments before posting them.
Trick 14 – I think the example could be a little clearer (particularly for someone like me who is new to numpy). I suggest:
import numpy def value_in_col(array, val, col): if val in array[:, col]: print(f'Value {val} occurs in column {col}') else: print(f'Value {val} does not occur in column {col}') arraySample = numpy.array([[1, 2], [3, 4], [4, 6], [7, 8]]) value_in_col(arraySample, 7, 0) value_in_col(arraySample, 7, 1)output:
Value 7 occurs in column 0
Value 7 does not occur in column 1
Trick 7 While your method certainly works, I think it would be simpler and clearer to define the function as follows:
Trick 2: It isn’t clear from your example why you need to use the symmetric_difference function rather just difference. Indeed your example does not require the use of symmetric_difference, difference() alone is adequate:
[‘Smith’, ‘Emma’]
The point of symmetric_difference is that it examines BOTH lists and includes the items that are unique to either of them.
To illustrate the use of symmetric_difference, I suggest the following re-wording and solution:
Sometimes you want to create a third list that contains all the items that appear in only one of two original lists and are absent from the other. Let’s see the best way to do this without looping and checking. To get all the differences you have to use the set’s symmetric difference operation.
[‘Emma’, ‘Scott’, ‘Smith’]