Typeerror nonetype object is not subscriptable python ошибка

У меня есть код:

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 сервер. У меня все ровно выскакивала данная ошибка. Что мне делать?

MaxU - stand with Ukraine's user avatar

задан 30 мая 2017 в 19:25

you have no pass 's user avatar

you have no pass you have no pass

3211 золотой знак2 серебряных знака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

Pavel Zaikin's user avatar

Возможным решением может быть обернуть весь код внутри 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

diralik's user avatar

diralikdiralik

9,2956 золотых знаков23 серебряных знака57 бронзовых знаков

17

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

List and tuple support indexing

List and tuple support indexing

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.

TypeError: 'NoneType' object is not subscriptable

TypeError: ‘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.

__getitem__ method is required for an item to be subscriptable

__getitem__ method is required for an item to be subscriptable

However, if you try the same for None, there won’t be a __getitem__ method. Which is the reason for the type error.

__getitem__ method is not present in the case of NoneType

__getitem__ method is not present in the case of NoneType

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.

TypeError on using sort method

TypeError on using sort method

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.

TypeError on using append method

TypeError on using the append method

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

TypeError on using reverse method

TypeError on using the reverse method

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

TypeError for sort resolved

TypeError for sort resolved

Solution for append() method

list_example = [1, 11, 14, 10, 5, 3, 2, 15, 77]
list_example.append(88)
print(list_example[-1])

TypeError for append resolved

TypeError for append resolved

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 for reverse resolved

TypeError for reverse resolved

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__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

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:PersonalIJSCodemain.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.

Avatar Of Srinivas Ramakrishna

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.

Python objects with the value None cannot be accessed using indexing. This is because None values do not contain data with index numbers.

If you try to access an item from a None value using indexing, you encounter a “TypeError: ‘NoneType’ object is not subscriptable” error.

Get offers and scholarships from top coding schools illustration

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.

Python objects with the value None cannot be accessed using indexing. This is because None values do not contain data with index numbers.

If you try to access an item from a None value using indexing, you encounter a “TypeError: ‘NoneType’ object is not subscriptable” error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what this error means and break down how it works. We walk through an example of this error so you can figure out how to solve it in your program.

TypeError: ‘NoneType’ object is not subscriptable

Subscriptable objects are values accessed using indexing. “Indexing” is another word to say “subscript”, which refers to working with individual parts of a larger collection.

For instance, lists, tuples, and dictionaries are all subscriptable objects. You can retrieve items from these objects using indexing. None values are not subscriptable because they are not part of any larger set of values.

The “TypeError: ‘NoneType’ object is not subscriptable” error is common if you assign the result of a built-in list method like sort(), reverse(), or append() to a variable. This is because these list methods change an existing list in-place. As a result, they return a None value.

An Example Scenario

Build an application that tracks information about a student’s test scores at school. We begin by defining a list of student test scores:

scores = [
	   { "name": "Tom", "score": 72, "grade": "B" },
	   { "name": "Lindsay", "score": 79, "grade": "A" }
]

Our list of student test scores contains two dictionaries. Next, we ask the user to insert information that should be added to the “scores” list:

name = input("Enter the name of the student: ")
score = input("Enter the test score the student earned: ")
grade = input("Enter the grade the student earned: ")

We track three pieces of data: the name of a student, their test score, and their test score represented as a letter grade.

Next, we append this information to our “scores” list. We do this by creating a dictionary which we will add to the list using the append() method:

new_scores = scores.append(
	{ "name": name, "score": score, "grade": grade }
)

This code adds a new record to the “scores” list. The result of the append() method is assigned to the variable “new_scores”.

Finally, print out the last item in our “new_scores” list so we can see if it worked:

The value -1 represents the last item in the list. Run our code and see what happens:

Enter the name of the student: Wendell
Enter the test score the student earned: 64
Enter the grade the student earned: C
Traceback (most recent call last):
  File "main.py", line 14, in <module>
	print(new_scores[-1])
TypeError: 'NoneType' object is not subscriptable

Our code returns an error.

The Solution

Our code successfully asks our user to insert information about a student. Our code then adds a record to the “new_scores” list. The problem is when we try to access an item from the “new_scores” list.

Our code does not work because append() returns None. This means we’re assigning a None value to “new_scores”. append() returns None because it adds an item to an existing list. The append() method does not create a new list.

To solve this error, we must remove the declaration of the “new_scores” variable and leave scores.append() on its own line:

scores.append(
	{ "name": name, "score": score, "grade": grade }
)
print(scores[-1])

We now only reference the “scores” variable. Let’s see what happens when we execute our program:

Enter the name of the student: Wendell
Enter the test score the student earned: 64
Enter the grade the student earned: C
{'name': 'Wendell', 'score': '64', 'grade': 'C'}

Our code runs successfully. First, our user is asked to insert information about a student’s test scores. Then, we add that information to the “scores” dictionary. Our code prints out the new dictionary value that has been added to our list so we know our code has worked.

Conclusion

The “TypeError: ‘NoneType’ object is not subscriptable” error is raised when you try to access items from a None value using indexing.

This is common if you use a built-in method to manipulate a list and assign the result of that method to a variable. Built-in methods return a None value which cannot be manipulated using the indexing syntax.

Now you’re ready to solve this common Python error like an expert.

Понравилась статья? Поделить с друзьями:
  • Typeerror int object is not callable ошибка
  • Typeerror function object is not subscriptable ошибка
  • Typeerror failed to fetch ошибка
  • Type object is not subscriptable python ошибка
  • Type object has no attribute objects ошибка