You might have worked with list, tuple, and dictionary data structures, the list and dictionary being mutable while the tuple is immutable. They all can store values. And additionally, values are retrieved by indexing. However, there will be times when you might index a type that doesn’t support it. Moreover, it might face an error similar to the error TypeError: ‘NoneType’ object is not subscriptable.
list_example = [1, 2, 3, "random", "text", 5.64] tuple_example = (1, 2, 3, "random", "text", 5.64) print(list_example[4]) print(list_example[5]) print(tuple_example[0]) print(tuple_example[3])
What is a TypeError?
The TypeError occurs when you try to operate on a value that does not support that operation. The most common reason for an error in a Python program is when a certain statement is not in accordance with the prescribed usage. The Python interpreter immediately raises a type error when it encounters an error, usually along with an explanation.
Let’s reproduce the type error we are getting:
On trying to index the var variable, which is of NoneType, we get an error. The ‘NoneType’ object is not subscriptable.
Let’s break down the error we are getting. Subscript is another term for indexing. Likewise, subscriptable means an indexable item. For instance, a list, string, or tuple is subscriptable. None in python represents a lack of value for instance, when a function doesn’t explicitly return anything, it returns None. Since the NoneType object is not subscriptable or, in other words, indexable. Hence, the error ‘NoneType’ object is not subscriptable.
An object can only be subscriptable if its class has __getitem__ method implemented.
By using the dir function on the list, we can see its method and attributes. One of which is the __getitem__ method. Similarly, if you will check for tuple, strings, and dictionary, __getitem__ will be present.
However, if you try the same for None, there won’t be a __getitem__ method. Which is the reason for the type error.
Resolving the ‘NoneType’ object is not subscriptable
The ‘NoneType’ object is not subscriptable and generally occurs when we assign the return of built-in methods like sort(), append(), and reverse(). What is the common thing among them? They all don’t return anything. They perform in-place operations on a list. However, if we try to assign the result of these functions to a variable, then None will get stored in it. For instance, let’s look at their examples.
Example 1: sort()
list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77] list_example_sorted = list_example.sort() print(list_example_sorted[0])
The sort() method sorts the list in ascending order. In the above code, list_example is sorted using the sort method and assigned to a new variable named list_example_sorted. On printing the 0th element, the ‘NoneType’ object is not subscriptable type error gets raised.
Recommended Reading | [Solved] TypeError: method Object is not Subscriptable
Example 2: append()
list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77] list_example_updated = list_example.append(88) print(list_example_updated[5])
The append() method accepts a value. The value is appended to t. In the above code, the return value of the append is stored in the list_example_updated variable. On printing the 5th element, the ‘NoneType’ object is not subscriptable type error gets raised.
Example 2: reverse()
Similar to the above examples, the reverse method doesn’t return anything. However, assigning the result to a variable will raise an error. Because the value stored is of NoneType.
list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77] list_example_reversed = list_example.reverse() print(list_example_reversed[5])
Recommended Reading | How to Solve TypeError: ‘int’ object is not Subscriptable
The solution to the ‘NoneType’ object is not subscriptable
It is important to realize that all three methods don’t return anything to resolve this error. This is why trying to store their result ends up being a NoneType. Therefore, avoid storing their result in a variable. Let’s see how we can do this, for instance:
Solution for sort() method
list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77] list_example.sort() print(list_example[0])
Solution for append() method
list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77] list_example.append(88) print(list_example[-1])
Solution for the reverse() method
list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77] list_example_reversed = list_example.reverse() print(list_example_reversed[5])
TypeError: ‘NoneType’ object is not subscriptable, JSON/Django/Flask/Pandas/CV2
The error, NoneType object is not subscriptable, means that you were trying to subscript a NoneType object. This resulted in a type error. ‘NoneType’ object is not subscriptable is the one thrown by python when you use the square bracket notation object[key] where an object doesn’t define the __getitem__ method. Check your code for something of this sort.
None[something]
FAQs
How to catch TypeError: ‘NoneType’ object is not subscriptable?
This type of error can be caught using the try-except block. For instance:try:
list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77]
list_sorted = list_example.sort()
print(list_sorted[0])
except TypeError as e:
print(e)
print("handled successfully")
How can we avoid the ‘NoneType’ object is not subscriptable?
It is important to realize that Nonetype objects aren’t indexable or subscriptable. Therefore an error gets raised. Hence, in order to avoid this error, make sure that you aren’t indexing a NoneType.
Conclusion
This article covered TypeError: ‘NoneType’ object is not subscriptable. We talked about what is a type error, why the ‘NoneType’ object is not subscriptable, and how to resolve it.
Other Python Errors You Might Get
-
[Solved] typeerror: unsupported format string passed to list.__format__
●May 31, 2023
-
Solving ‘Remote End Closed Connection’ in Python!
by Namrata Gulati●May 31, 2023
-
[Fixed] io.unsupportedoperation: not Writable in Python
by Namrata Gulati●May 31, 2023
-
[Fixing] Invalid ISOformat Strings in Python!
by Namrata Gulati●May 31, 2023
When working with Python, attempting to access an index or slice of an object that has the value None
may result in TypeError: 'NoneType' object is not subscriptable
. Let’s delve into why this TypeError occurs and how to resolve it.
None
is a unique constant in Python that stands in for the lack of a value. It is employed to show that a variable or expression does not possess a value. The Python built-in class NoneType
has an object called None
that belongs to it. An instance of NoneType
is assigned to a variable when None
is assigned to it.
For Example:
my_var = None
print(type(my_var))
Output:
<class 'NoneType'>
What Causes TypeError: ‘NoneType’ And How to Fix this Error
Working with NoneType objects frequently results in the 'NoneType' object is not subscriptable
error. The issue arises when you try to use the index or key of a NoneType
object as if it were a list or dictionary. Python raises this error because NoneType
objects do not support indexing or key access, preventing the programmer from doing an invalid operation. The following are some typical situations that may result in this issue and the solutions to fix them:
1. Forgetting to Assign a Value to a Variable
If you forget to assign a value to a variable, it will default to a NoneType
object. If you then try to access an index or a key of that variable, Python will raise the 'NoneType' object is not subscriptable
error.
Example One
my_list = None
print(my_list[0])
Output: Example One
Traceback (most recent call last):
File "<string>", line 2, in <module>
TypeError: 'NoneType' object is not subscriptable
Solution One: Assigning a Value to the Variable
To fix the error it is essential to make sure to assign a value to the variable before trying to access its elements.
my_list = [1, 2, 3]
print(my_list[0])
Solution Two: Verifying if the object is not None
Another better way to do this is to add a check to make sure the object is not None
before we try to access it.
my_list = None
if my_list is not None:
print(my_list[0])
2. Not checking for NoneType objects
In some cases, you may receive a NoneType
object from a function or a method. If you then try to access an index or key of that object without first checking if it is not None, Python will raise the 'NoneType' object is not subscriptable
error.
Example Two
def get_user(id):
# Implementation omitted
return None
user = get_user(123)
print(user['name'])
Output: Example Two
Traceback (most recent call last):
File "<string>", line 6, in <module>
TypeError: 'NoneType' object is not subscriptable
Solution Example Two
In order to fix the error, make sure to check if the object is not None
before trying to access its elements.
def get_user(id):
# Implementation omitted
return None
user = get_user(123)
if user is not None:
print(user['name'])
else:
print("User not found")
Conclusion
In summary, the NoneType object is not subscriptable
error is a typical Python error that happens when we attempt to access an index or a key of a variable that is of the NoneType
data type. This error usually occurs when a method or a function returns None
rather than the desired value.
You must make sure that all of the functions and methods return values of the required type in order to fix this error. Additionally, you must always explicitly check for None
before attempting to access any indices or keys of the returned item. By following these best practices, you can avoid this error and ensure that the Python code runs correctly.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
У меня есть код:
from bs4 import BeautifulSoup
import requests
head = {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1)'}
proxi = {
'http': 'http://195.9.149.198:8081',
}
query = input('What are you searching for?: ' )
number = input('How many pages: ' )
url ='http://www.google.com/search?q='
page = requests.get(url + query, headers=head, proxies=proxi)
for index in range(int(number)):
soup = BeautifulSoup(page.text, "html.parser")
next_page=soup.find("a",class_="fl")
next_link=("https://www.google.com"+next_page["href"])
h3 = soup.find_all("h3",class_="r")
for elem in h3:
elem=elem.contents[0]
link=("https://www.google.com" + elem["href"])
print(link)
page = requests.get(next_link)
Пол дня проработав с данным кодом, послав множественное количества запросов для парсинга url адресов у меня шло все отлично, кроме того когда я добавлял inurl:
Данный код работал безупречно. Но вот через кое-какое количество запросов у меня уже выползала постоянно ошибка TypeError: 'NoneType' object is not subscriptable
даже не добавляя inurl:
Я так понял, что появляется капча, и пишется что из моей сети исходит очень подозрительный трафик. И из-за этого блокирует, попробовав добавить headers
и делать данное действие через proxi
сервер. У меня все ровно выскакивала данная ошибка. Что мне делать?
задан 30 мая 2017 в 19:25
you have no pass you have no pass
3211 золотой знак3 серебряных знака13 бронзовых знаков
2
TypeError: ‘NoneType’ object is not subscriptable
Возникает тогда, когда вы пытаетесь по индексу обратиться к None Объекту.
>>> t = None
>>> t[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable
Проверяйте обращение по индексу (там в ошибке должен быть номер строки)
ответ дан 17 июл 2017 в 5:45
Возможным решением может быть обернуть весь код внутри for
в try...except
, а в месте обработки ошибки засыпать на некоторое время. Мне кажется хорошей идеей немного увеличивать это время после каждой капчи. Например, начать со значения равного пяти секундам, и увеличивать на одну секунду. Возможная реализация:
from time import sleep
from bs4 import BeautifulSoup
import requests
head = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1)'}
proxi = {
'http': 'http://195.9.149.198:8081',
}
time_to_sleep_when_captcha = 5
query = input('What are you searching for?: ')
number = input('How many pages: ')
url = 'http://www.google.com/search?q='
page = requests.get(url + query, headers=head, proxies=proxi)
for index in range(int(number)):
try:
soup = BeautifulSoup(page.text, "html.parser")
next_page = soup.find("a", class_="fl")
next_link = ("https://www.google.com" + next_page["href"])
h3 = soup.find_all("h3", class_="r")
for elem in h3:
elem = elem.contents[0]
link = ("https://www.google.com" + elem["href"])
print(link)
page = requests.get(next_link)
except:
sleep(time_to_sleep_when_captcha)
time_to_sleep_when_captcha += 1
ответ дан 30 мая 2017 в 19:39
diralikdiralik
9,3256 золотых знаков23 серебряных знака57 бронзовых знаков
17
In Python, NoneType is the type for the None object, which is an object that indicates no value. Functions that do not return anything return None, for example, append()
and sort()
. You cannot retrieve items from a None value using the subscript operator []
like you can with a list or a tuple. If you try to use the subscript operator on a None value, you will raise the TypeError: NoneType object is not subscriptable.
To solve this error, ensure that when using a function that returns None
, you do not assign its return value to a variable with the same name as a subscriptable object that you will use in the program.
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
- TypeError: ‘NoneType’ object is not subscriptable
- Example #1: Appending to a List
- Solution
- Example #2: Sorting a List
- Solution
- Summary
TypeError: ‘NoneType’ object is not subscriptable
Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type.
The subscript operator retrieves items from subscriptable objects. The operator in fact calls the __getitem__
method, for example a[i]
is equivalent to a.__getitem__(i)
.
All subscriptable objects have a __getitem__
method. NoneType objects do not contain items and do not have a __getitem__
method. We can verify that None objects do not have the __getitem__
method by passing None
to the dir()
function:
print(dir(None))
['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
If we try to subscript a None value, we will raise the TypeError: ‘NoneType’ object is not subscriptable.
Example #1: Appending to a List
Let’s look at an example where we want to append an integer to a list of integers.
lst = [1, 2, 3, 4, 5, 6, 7] lst = lst.append(8) print(f'First element in list: {lst[0]}')
In the above code, we assign the result of the append call to the variable name lst
. Let’s run the code to see what happens:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [1], in <cell line: 5>() 1 lst = [1, 2, 3, 4, 5, 6, 7] 3 lst = lst.append(8) ----> 5 print(f'First element in list: {lst[0]}') TypeError: 'NoneType' object is not subscriptable
We throw the TypeError because we replaced the list with a None value. We can verify this by using the type() method.
lst = [1, 2, 3, 4, 5, 6, 7] lst = lst.append(8) print(type(lst))
<class 'NoneType'>
When we tried to get the first element in the list, we are trying to get the first element in the None object, which is not subscriptable.
Solution
Because append()
is an in-place operation, we do not need to assign the result to a variable. Let’s look at the revised code:
lst = [1, 2, 3, 4, 5, 6, 7] lst.append(8) print(f'First element in list: {lst[0]}')
Let’s run the code to get the result:
First element in list: 1
We successfully retrieved the first item in the list after appending a value to it.
Example #2: Sorting a List
Let’s look at an example where we want to sort a list of integers.
numbers = [10, 1, 8, 3, 5, 4, 20, 0] numbers = numbers.sort() print(f'Largest number in list is {numbers[-1]}')
In the above code, we assign the result of the sort() call to the variable name numbers. Let’s run the code to see what happens:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [8], in <cell line: 3>() 1 numbers = [10, 1, 8, 3, 5, 4, 20, 0] 2 numbers = numbers.sort() ----> 3 print(f'Largest number in list is {numbers[-1]}') TypeError: 'NoneType' object is not subscriptable
We throw the TypeError because we replaced the list numbers
with a None
value. We can verify this by using the type()
method.
numbers = [10, 1, 8, 3, 5, 4, 20, 0] numbers = numbers.sort() print(type(numbers))
<class 'NoneType'>
When we tried to get the last element of the sorted list, we are trying to get the last element in the None object, which is not subscriptable.
Solution
Because sort()
is an in-place operation, we do not need to assign the result to a variable. Let’s look at the revised code:
numbers = [10, 1, 8, 3, 5, 4, 20, 0] numbers.sort() print(f'Largest number in list is {numbers[-1]}')
Let’s run the code to get the result:
Largest number in list is 20
We successfully sorted the list and retrieved the last value of the list.
Summary
Congratulations on reading to the end of this tutorial! The TypeError: ‘NoneType’ object is not subscriptable occurs when you try to retrieve items from a None value using indexing. If you are using in-place operations like append, insert, and sort, you do not need to assign the result to a variable.
For further reading on TypeErrors, go to the articles:
- How to Solve Python TypeError: ‘function’ object is not subscriptable
- How to Solve Python TypeError: ‘bool’ object is not subscriptable
Go to the online courses page on Python to learn more about Python for data science and machine learning.
Have fun and happy researching!
If you subscript any object with None value, Python will raise TypeError: ‘NoneType’ object is not subscriptable exception. The term subscript means retrieving the values using indexing.
In this tutorial, we will learn what is NoneType object is not subscriptable error means and how to resolve this TypeError in your program with examples.
In Python, the objects that implement the __getitem__
method are called subscriptable objects. For example, lists, dictionaries, tuples are all subscriptable objects. We can retrieve the items from these objects using Indexing.
The TypeError: ‘NoneType’ object is not subscriptable error is the most common exception in Python, and it will occur if you assign the result of built-in methods like append()
, sort()
, and reverse()
to a variable.
When you assign these methods to a variable, it returns a None
value. Let’s take an example and see if we can reproduce this issue.
numbers = [4, 5, 7, 1, 3, 6, 9, 8, 0]
output = numbers.sort()
print("The Value in the output variable is:", output)
print(output[0])
Output
The Value in the output variable is: None
Traceback (most recent call last):
File "c:\Personal\IJS\Code\main.py", line 9, in <module>
print(output[0])
TypeError: 'NoneType' object is not subscriptable
If you look at the above example, we have a list with some random numbers, and we tried sorting the list using a built-in sort()
method and assigned that to an output variable.
When we print the output variable, we get the value as None. In the next step, we are trying to access the element by indexing, thinking it is of type list, and we get TypeError: ‘NoneType’ object is not subscriptable.
You will get the same error if you perform other operations like append()
, reverse()
, etc., to the subscriptable objects like lists, dictionaries, and tuples. It is a design principle for all mutable data structures in Python.
Note: Python doesn't allow to subscript the integer objects if you do Python will raise TypeError: 'int' object is not subscriptable
TypeError: ‘NoneType’ object is not subscriptable Solution
Now that you have understood, we get the TypeError when we try to perform indexing on the None
Value. We will see different ways to resolve the issues.
Our above code was throwing TypeError because the sort()
method was returning None value, and we were assigning the None value to an output variable and indexing it.
The best way to resolve this issue is by not assigning the sort()
method to any variable and leaving the numbers.sort()
as is.
Let’s fix the issue by removing the output variable in our above example and run the code.
numbers = [4, 5, 7, 1, 3, 6, 9, 8, 0]
numbers.sort()
output = numbers[2]
print("The Value in the output variable is:", output)
print(output)
Output
The Value in the output variable is: 3
3
If you look at the above code, we are sorting the list but not assigning it to any variable.
Also, If we need to get the element after sorting, then we should index the original list variable and store it into a variable as shown in the above code.
Conclusion
The TypeError: ‘ NoneType’ object is not subscriptable error is raised when you try to access items from a None value using indexing.
Most developers make this common mistake while manipulating subscriptable objects like lists, dictionaries, and tuples. All these built-in methods return a None
value, and this cannot be assigned to a variable and indexed.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.