Home / Blog / Data Science / Python - TypeError – NoneType Object not Subscriptable

Python - TypeError – NoneType Object not Subscriptable

  • July 06, 2023
  • 35084
  • 23
Author Images

Meet the Author : Mr. Bharani Kumar

Bharani Kumar Depuru is a well known IT personality from Hyderabad. He is the Founder and Director of Innodatatics Pvt Ltd and 360DigiTMG. Bharani Kumar is an IIT and ISB alumni with more than 18+ years of experience, he held prominent positions in the IT elites like HSBC, ITC Infotech, Infosys, and Deloitte. He is a prevalent IT consultant specializing in Industrial Revolution 4.0 implementation, Data Analytics practice setup, Artificial Intelligence, Big Data Analytics, Industrial IoT, Business Intelligence and Business Management. Bharani Kumar is also the chief trainer at 360DigiTMG with more than Ten years of experience and has been making the IT transition journey easy for his students. 360DigiTMG is at the forefront of delivering quality education, thereby bridging the gap between academia and industry.

Read More >

Error!! Error!!! Error!!!! These are common popups we get while executing code, we might feel panic or irritated when we see such errors. But error notifications are actually problem solvers, every error will be identified with the proper error name which helps us to fix the error in the right direction.

Due to COVID-19 lockout, a group of pals who were working on Python together and getting various issues started talking about their errors.

The dialogue between them will now begin.

Ram: Oops!! I just got an error ☹

What error did you get? : Nithin

Ram: I got a None-Type object not subscriptable error!

Oh really, I got the same error too
in yesterday’s task. : Yash

Ram: You were working on a different task but
still you got the same error? Strange!

Oh, is it? how come the same error for different tasks : Yash

So, there is nothing much strange here!
They are an absolute change of getting the same error for different cases.
I have a few examples lets discuss it. : Nitin

TypeError: 'NoneType' object is not subscriptable

The mistake is self-evident. You are attempting to subscript an object that is actually a None.

Example 1

list1=[5,1,2,6]        # Create a simple list
order=list1.sort()  # sort the elements in created list and store into another variable.
order[0]               # Trying to access the first element after sorting

 

TypeError     Traceback (most recent call last)

in ()
  list1=[5,1,2,6]
  order=list1.sort()
----> order[0]

TypeError: 'NoneType' object is not subscriptable

Sort () function returns None due to TypeError: 'NoneType' object is not subscriptable. It affects the source item directly. So you're attempting to slice or subscript the empty None object.

print(order)  # Let’s see the data present in the order variable.
None        # It’s None

REMEDY

Sort () function returns None due to TypeError: 'NoneType' object is not subscriptable. It affects the source item directly. So you're attempting to slice or subscript the empty None object.Verify whether the returned value is None by looking at it. If it's None, then make appropriate plans for the alternatives.

We are attempting to sort the values in a list in the example above. When sort() is called, the source object is changed without any output being produced. To fix the problem, we might attempt other approaches.

  • either operate on the source directly.

    list1=[5,1,2,6] #A simple List
    list1.sort()    # Sort the elements of source object directly.
    list1[0]         # Access the first element of the sorted list.
    Output: 1

  • or use another method that returns the object with sorted values of the list.

    list1=[5,1,2,6]              # A simple list created
    order=sorted(list1)   # Sorting the elements of the above list and store them into another list.
    order[0]                   # Access first element of a new list created.

     

    Output: 1

    Example 2

    list1=[1,2,4,6]                            # Create a list with a few elements
    reverse_order=list1.reverse()   # Reverse the order of elements and store into other variable.
    reverse_order[0:2]                    # Access the first two elements after reversing the order.

     


    TypeError     Traceback (most recent call last)

    in ()
          list1=[1,2,4,6]
          reverse_order=list1.reverse()
    ----> reverse_order[0:2]

    TypeError: 'NoneType' object is not subscriptable

    the reverse() method also won't return anything but None, it directly acts upon the source object. So you are trying to slice/subscript the None object which holds no data at all.

    print(reverse_order)     # Prints the data inside reverse_order

    None   #It’s None
    REMEDY

    Always verify whether None is present in the returned values. If it's None, then consider your options carefully.

    The items of a list are being attempted to be reversed in the example above. Reverse() does not return anything; instead, it changes the source object. To fix the problem, we might attempt other approaches.

    • Either operate on the source directly.

      list1=[1,2,4,6]  #A simple list
      list1.reverse()  # Reverse the order of elements in the above list
      list1[0:2]          # Accessing the first two elements in a reversed list.

      Output: [6, 4]

    • Use another method that returns the object with reversed values of the list.

      list1=[1,2,4,6]                              # A list
      reverse_order=list(reversed(list1))  # Reversing the order and store into another list.
      reverse_order[0:2]                          # Accessing the first 2 elements of reversed list.

      Output: [6, 4]

    Example 3

    Import numpy as np     # Import numpy package

    def addition(arrays):          # A function which performs addition operation
    total=arrays.sum(axis=1)  # Performing row wise addition in numpy array

    a=np.arange(12).reshape(6,2)   #Creating a 2D array
    total=addition(a)                         #Calling the function
    total[0:4]                                     #Accessing first 4 elements on total


    TypeError     Traceback (most recent call last)

    in ()

         a=np.arange(12).reshape(6,2)
         total=addition(a)
    ----> total[0:4]

    TypeError: 'NoneType' object is not subscriptable

    As we can see, the addition function in this case is not returning anything. The resulting object will yield the aforementioned error when we attempt to subscript it because it contains nothing.

    print(total) #print total
    None

    REMEDY

    Always verify whether None is present in the returned values. If it's None, then consider your options carefully.

    In the example above, we're attempting to display the total of a 2D array's row-wise items. To fix the problem, we might attempt other approaches.

    • Either print the sum inside the function directly.

      import numpy as np   # Import numpy package for mathematical operations

      defaddition1(arrays):                   # Function to perform addition
      total1=arrays.sum(axis=1)          # Row-wise sum in 2D numpy array
      print('row wise sum',total1[0:4])  # Printing first 4 elements of total

      a=np.arange(12).reshape(6,2)  # Creating a 2D array
      print('input array \n',a)               # Printing a comment
      print('*********')
      addition1(a)                              # Calling the function

      input array
      [[ 0 1]
      [ 2 3]
      [ 4 5]
      [ 6 7]
      [ 8 9]
      [10 11]]
      *********

      row wise sum [ 1 5 9 13]

    • import numpy as np   # Import numpy package

      defaddition2(arrays):  # Defining a function which performs addition
      return total                 # Returning the sum

       a=np.arange(12).reshape(6,2)  # Creating a 2D array
      print('input array \n',a)
      print('*********')
      total2= addition2(a)                      # Calling the function
      print('row wise sum',total2[0:4])   # Printing first 4 elements of total

      input array
      [[ 0 1]
      [ 2 3]
      [ 4 5]
      [ 6 7]
      [ 8 9]
      [10 11]]
      *********
      row wise sum [ 1 5 9 13]

    Watch Free Videos on Youtube

    Example4

    import cv2                                           # Importing opencv package to read the image
    import numpy as np                           # Importing numpy package
    import matplotlib.pyplot as plt            # Package for visualization
    image=cv2.imread('download.jpeg')    # Reading the image
    plt.imshow(image[65:120])               # Show the part of image


    TypeError     Traceback (most recent call last)

    in ()
          importmatplotlib.pyplotasplt
          image=cv2.imread('download.jpeg')
    ----> plt.imshow(image[65:120])

    TypeError: 'NoneType' object is not subscriptable

    Here we are trying to print a cut short of the image. Above error which is coming as OpenCV is unable to read the image

    print(image)
    None

    REMEDY

    Look for the proper path, then fix the image's format. OpenCV won't be able to load the image if the path or image type are incorrect. The picture type is 'jpg' here rather than 'jpeg.'

    import cv2                                   # Import opencv package to read the image
    import numpy as np                         # Numpy package
    import matplotlib.pyplot as plt          # For visualization
    image=cv2.imread('download.jpg')  # Reading the image
    plt.imshow(image[65:120])              # Showing the part of image

    Output:

    TypeError: 'NoneType' object is not subscriptable

    Conclusion: We frequently encounter the TypeError issue while attempting to compute across incompatible data types. Anytime we attempt to subscript or slice an empty data object or data of no type, we encounter the TypeError: None-type not subscriptable error.

Click here to learn Data Science Course, Data Science Course in Hyderabad, Data Science Course in Bangalore

Data Science Placement Success Story

Data Science Training Institutes in Other Locations

Data Analyst Courses in Other Locations

Navigate to Address

360DigiTMG - Data Science, IR 4.0, AI, Machine Learning Training in Malaysia

Level 16, 1 Sentral, Jalan Stesen Sentral 5, Kuala Lumpur Sentral, 50470 Kuala Lumpur, Wilayah Persekutuan Kuala Lumpur, Malaysia

+60 19-383 1378

Get Direction: Data Science Course

Read
Success Stories
Make an Enquiry

Celebrate this festival with Learning! Unlock Your Future with Our Special Festival Discounts!! Know More