Python - TypeError – NoneType Object not Subscriptable

Python - TypeError – NoneType Object not Subscriptable | 360DigiTMG

 

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.

A Group of friends is living together due to COVID-19 lockdown, they are working on Python and they got different errors individually and started discussing their errors.

So, here goes the discussion between them.

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 error is self-explanatory. You are trying to subscript an object which is a None actually...

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 () method won't return anything but None. It directly acts upon source object. So, you are trying to slice/subscript the None object which holds no data at all.

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

REMEDY

Check for the returned value whether it is None. If it is None, then plan for the alternatives accordingly.

In the above example, we are trying to sort the values in a list. when sort() is used, the source object itself gets modified, without returning anything. We can try other ways to get the error resolved.

  • 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 check for the returned values whether it is None. If it is None, then plan the alternatives accordingly.

    In the above example, we are trying to reverse the elements of a list. when reverse() is used, the source object itself gets modified, without returning anything. We can try other ways to get the error resolved.

    • 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

    Here if we observe, the function addition is not returning anything. When we try to subscript the returned object it will give the above error as it holds nothing.

    print(total) #print total
    None

    REMEDY

    Always check for the returned values whether it is None. If it is None, then plan the alternatives accordingly.

    In the above example, we are trying to print the sum of the row-wise elements in a 2D array. We can try other ways to get the error resolved.

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

    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 correct path and correct the format of the image. If the path is wrong or the image type is wrong then, OpenCV won't able to load the image. Here the image type is 'jpg' not '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: The TypeError is a common error message we get while we are computing different data types which are not compatible. Whenever we are trying to subscript/slice the none type data(object/value) or empty data object then we will get the TypeError: None-type not subscriptable error.

Comments