PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
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 | 23 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)Code language: Python (python)

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.

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

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

list3 = list(set1.symmetric_difference(set2))
print(list3)Code language: Python (python)

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))Code language: Python (python)

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)Code language: Python (python)

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))Code language: Python (python)

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.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))Code language: Python (python)

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))Code language: Python (python)

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 )Code language: Python (python)

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)Code language: Python (python)

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:

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

allEmployee = {**currentEmployee, **formerEmployee}
print(allEmployee)Code language: Python (python)

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))
Code language: Python (python)

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)Code language: Python (python)

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))Code language: Python (python)

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))Code language: Python (python)

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)Code language: Python (python)

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)Code language: Python (python)

Tip and Trick 15: range for float numbers

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有

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

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
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 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Calvin Au says

    December 16, 2023 at 5:55 pm

    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!

    Reply
  2. Nambativ says

    July 7, 2023 at 8:42 am

    Sir i have two coding challenges would like to share with you, so you can provide your solutions in PYTHON

    Reply
  3. hakizimana frederick says

    December 14, 2021 at 5:42 pm

    
    def is_palindrome(n):
        if type(n) == int:
            reversed = str(n)[::-1]
            if reversed == str(n):
                return True
        return False
    
    print(is_palindrome(545))
    Reply
    • Carmelo says

      June 11, 2022 at 3:57 pm

      def is_palindrome(string):
           if isinstance(string, int):
               string = str(string)
           return string[:] == string[::-1]
      Reply
      • Carmelo says

        June 11, 2022 at 3:59 pm

        def is_palindrome(string):
                      if isinstance(string, int):
                         string = str(string)
                      return string[:] == string[::-1]
        Reply
  4. wcom says

    November 6, 2021 at 10:30 pm

    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

    Reply
    • Nothing says

      January 22, 2022 at 10:59 pm

      You’re thinking that, we don’t to write in a shorter way.

      if we write in this way means beginners will also understand

      Reply
  5. VladimirJosephStephanSolodkovOrlovsky says

    February 14, 2021 at 8:14 am

    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)

    ……………………Totally unnecessary !!!!

    import time
    startTime = time.time()
    # write your code or functions calls
    totalTime = time.time() - startTime
    print("Total time required to execute code is= ", totalTime)

    even shorter ………………………….

    import time
    startTime = time.time()
    # write your code or functions calls
    print("Total time required to execute code is= ", time.time() - startTime)
    Reply
    • Rodrigo Nery says

      July 8, 2021 at 12:01 pm

      from time import time

      print(“Total time required to execute code is= “, time() – time())

      😛

      Reply
      • paras says

        July 12, 2021 at 10:17 pm

        Lmao man. More power to this comment.

        Reply
      • Steve says

        October 24, 2021 at 4:09 pm

        What’s this one measuring?

        Reply
  6. Venky says

    January 11, 2021 at 12:40 pm

    Hi,

    Why the below code is not working in Python 2.7 version?

    currentEmployee = {1: 'Scott', 2: "Eric", 3:"Kelly"}
    formerEmployee  = {2: 'Eric', 4: "Emma"}
    
    allEmployee = {**currentEmployee, **formerEmployee}
    print(allEmployee)

    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'}
    Reply
    • mendem says

      January 17, 2023 at 7:30 pm

      something

      Reply
    • Hamid says

      May 17, 2024 at 9:00 pm

      Change
      print(allEmployee)
      to
      print allEmployee

      Reply
  7. Digvijay kumar says

    April 1, 2020 at 3:49 pm

    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 False
    
    Reply
    • Aishwarya says

      April 12, 2020 at 9:10 pm

      hello!!! it says that i in range(0, len(n)-1) if the i and i+1==6 then the boolean value should be true if not it should be false

      Reply
    • Steve says

      October 24, 2021 at 4:29 pm

      Returns true if 2 numbers in an array are both sixes and side by side.

      Variable

      i

      goes through numbers in the range of 0 to the number of items in the list minus one.

      What’s coming up in the

      if

      statement is called “slice”. That looks like this:

      [starting_index:ending_index]

      the ending index is exclusive, that just means it’s not included in the evaluation. That’s why they used

      i+2

      to get the neighbor of i instead of

      i+1

      .

      If the sliced section of the list is equal to

      [6, 6

      ], it evaluates to

      true

      and then returns

      true

      . If it never evaluates to

      true

      , it returns

      false

      .

      Reply
      • Steve says

        October 24, 2021 at 4:32 pm

        Lol, didn’t know how code formatting worked on this site. My answer is still understandable but weird now.

        Reply
  8. Roger Demetrescu says

    September 12, 2019 at 7:28 pm

    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)

    Reply
    • Roger Demetrescu says

      September 12, 2019 at 7:32 pm

      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.

      Reply
  9. Bill Hardwick says

    May 19, 2019 at 6:04 pm

    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

    Reply
  10. Bill Hardwick says

    May 19, 2019 at 4:36 pm

    Trick 7 While your method certainly works, I think it would be simpler and clearer to define the function as follows:

    def isUnique(item):
      return len(item) == len(list(set(item)))
    
    Reply
  11. Bill Hardwick says

    May 19, 2019 at 3:56 pm

    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:

    list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
    list2 = ['Scott', 'Eric', 'Kelly']
    set1 = set(list1)
    set2 = set(list2)
    list3 = list(set1.difference(set2))
    print(list3)
    

    [‘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.

    list1 = ['Eric', 'Kelly', 'Emma', 'Smith']
    list2 = ['Scott', 'Eric', 'Kelly']
    
    set1 = set(list1)
    set2 = set(list2)
    list3 = list(set1.symmetric_difference(set2))
    print(list3)
    

    [‘Emma’, ‘Scott’, ‘Smith’]

    Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercises for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercises
  • Loop Exercises
  • Functions Exercises
  • String Exercises
  • List Exercises
  • Dictionary Exercises
  • Set Exercises
  • Tuple Exercises
  • Data Structure Exercises
  • Date and Time Exercises
  • OOP Exercises
  • File Handling Exercises
  • Iterators & Generators Exercises
  • Regex Exercises
  • Python JSON Exercises
  • Random Data Generation Exercises
  • NumPy Exercises
  • Pandas Exercises
  • Matplotlib Exercises
  • Python Database Exercises

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview 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.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

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
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有