PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Useful Python Tips and Tricks Every Programmer Should Know

Useful Python Tips and Tricks Every Programmer Should Know

Updated on: May 17, 2021 | 20 Comments

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.

import time

startTime = time.time()

# write your code or functions calls

endTime = time.time()
totalTime = endTime - startTime

print("Total time required to execute code is= ", totalTime)

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']

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.

list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
list2 = ['Scott', 'Eric', 'Kelly']

set1 = set(list1)
set2 = set(list2)

list3 = list(set1.symmetric_difference(set2))
print(list3)

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.

import sys

list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
print("size of list = ",sys.getsizeof(list1))

name = 'pynative.com'
print("size of name = ",sys.getsizeof(name))

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.

listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]
print("Original= ", listNumbers)

listNumbers = list(set(listNumbers))
print("After removing duplicate= ", listNumbers)

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.

listOne = [20, 20, 20, 20]
print("All element are duplicate in listOne", listOne.count(listOne[0]) == len(listOne))

listTwo = [20, 20, 20, 50]
print("All element are duplicate in listTwo", listTwo.count(listTwo[0]) == len(listTwo))

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]

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.Counter method if our object is hashable.
  • We can use sorted()if objects are orderable.
from collections import Counter

one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]

print("is two list are b equal", Counter(one) == Counter(two))

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.

def isUnique(item):
    tempSet = set()
    return not any(i in tempSet or tempSet.add(i) for i in item)

listOne = [123, 345, 456, 23, 567]
print("All List elemtnts are Unique ", isUnique(listOne))

listTwo = [123, 345, 567, 23, 567]
print("All List elemtnts are Unique ", isUnique(listTwo))

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.

byteVar = b"pynative"
str = str(byteVar.decode("utf-8"))
print("Byte to string is" , str )

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.

listOne = [123, 345, 456, 23]
print("Using enumerate")
for index, element in enumerate(listOne): 
    print("Index [", index,"]", "Value", element)

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"}

And you want these two dictionaries merged. Let see how to do this.

In Python 3.5 and above:

currentEmployee = {1: 'Scott', 2: "Eric", 3:"Kelly"}
formerEmployee  = {2: 'Eric', 4: "Emma"}

allEmployee = {**currentEmployee, **formerEmployee}
print(allEmployee)

In Python 2, or 3.4 and lower

currentEmployee = {1: 'Scott', 2: "Eric", 3:"Kelly"}
formerEmployee  = {2: 'Eric', 4: "Emma"}

def merge_dicts(dictOne, dictTwo):
    dictThree = dictOne.copy()
    dictThree.update(dictTwo)
    return dictThree
    
print(merge_dicts(currentEmployee, formerEmployee))

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.

ItemId = [54, 65, 76]
names = ["Hard Disk", "Laptop", "RAM"]

itemDictionary = dict(zip(ItemId, names))

print(itemDictionary)

Tip and Trick 11: Convert hex string, String to int

hexNumber = "0xfde"
stringNumber="34"

print("Hext toint", int(hexNumber, 0))
print("String to int", int(stringNumber, 0))

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.

number= 88.2345
print('{0:.2f}'.format(number))

Tip and Trick 13: Return multiple values from a function

def multiplication_Division(num1, num2):
  return num1*num2, num2/num1

product, division = multiplication_Division(10, 20)
print("Product", product, "Division", division)

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.

import numpy

arraySample = numpy.array([[1, 2], [3, 4], [4, 6], [7, 8]])

if value in arraySample[:, col_num]:
    print(value)

Tip and Trick 15: range for float numbers

Filed Under: Python, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Exercises
TweetF  sharein  shareP  Pin

 Python Exercises

  • Python Exercises Home
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com