list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
MASTERLIST = [list1, list2, list3]
def printer(lst):
print ("Available Lists:")
for x in range(len(lst)):
print (lst[x])[0]
This code is returning the «‘NoneType’ object is not subscriptable» error when I try and run
printer(MASTERLIST)
What did I do wrong?
tripleee
174k33 gold badges271 silver badges313 bronze badges
asked Sep 18, 2013 at 7:52
2
The print()
function returns None
. You are trying to index None. You can not, because 'NoneType' object is not subscriptable
.
Put the [0]
inside the brackets. Now you’re printing everything, and not just the first term.
answered Sep 18, 2013 at 8:00
TerryATerryA
58.6k11 gold badges114 silver badges142 bronze badges
The [0]
needs to be inside the )
.
answered Sep 18, 2013 at 7:54
Ethan FurmanEthan Furman
62.7k19 gold badges155 silver badges229 bronze badges
0
Don’t use list
as a variable name for it shadows the builtin.
And there is no need to determine the length of the list. Just iterate over it.
def printer(data):
for element in data:
print(element[0])
Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.
answered Sep 18, 2013 at 8:24
MatthiasMatthias
12.8k6 gold badges42 silver badges47 bronze badges
Point A: Don’t use list as a variable name
Point B: You don’t need the [0] just
print(list[x])
answered Oct 24, 2016 at 22:25
Cam92Cam92
214 bronze badges
The indexing e.g. [0] should occour inside of the print…
answered Mar 25, 2017 at 12:48
keremistankeremistan
4144 silver badges17 bronze badges
list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
def printer(*lists):
for _list in lists:
for ele in _list:
print(ele, end = ", ")
print()
printer(list1, list2, list3)
answered Mar 25, 2017 at 12:54
Joshua NixonJoshua Nixon
1,3792 gold badges12 silver badges25 bronze badges
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
-
[Fixed] SSL module in Python is Not Available
●May 30, 2023
-
[Fixed] modulenotfounderror: no module named ‘_bz2
by Namrata Gulati●May 2, 2023
-
[Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled
by Namrata Gulati●May 2, 2023
-
Prevent Errors with Python deque Empty Handling
by Namrata Gulati●May 2, 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!
Блин, точно, невнимательный очень.
Спасибо вам большое.
Еще вопрос есть, может подскажете если сможете.
Получается у меня не правильно всё равно отображается результат.
Получается я сперва вытаскиваю 3 столбца, это: Лига, Количество Игр, Проходимость
Затем я фильтрую каждый столбец. Количество игр >5, проходимость >70%.
Далее мне нужно все это совместить и вывести:
Я делаю вот так, но shell ругается
Кликните здесь для просмотра всего текста
Python | ||
|
Traceback (most recent call last):
File «C:UsersAdministratorDesktopbasketballfirst_quarter.py», line 60, in <module>
for i in range(proc):
TypeError: ‘list’ object cannot be interpreted as an integer
Добавлено через 1 минуту
Хорошо, спасибо. Я просто на курсы хожу 3 недели. Нам вот так пока объясняют всё, видимо чтоб понимать как всё устроено
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.
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.