I’m writing a small math-related Python script, and I ran into this error:
TypeError: ‘NoneType’ object is not subscriptable
Here’s the relevant part of my code:
lista = [v1, v3]
lista = list.sort(lista) # I think the issue starts here
a = lista[1] - lista[0]
I’m trying to sort the list and then use the values by index. I later got the same issue when doing:
list = [v2, v4]
list = list.sort(list)
b = list[1] - list[0]
After some debugging, it seems lista (and later list) becomes None, which triggers the error when I try to access an index.
I’d appreciate help understanding why this typeerror: ‘nonetype’ object is not subscriptable happens here, and what the correct way is to sort a list and still use its contents afterward.
"I’ve run into this TypeError: ‘NoneType’ object is not subscriptable a few times, and it often happens when using the result of list.sort()
, which always returns None
. The thing is, list.sort()
sorts the list in place and doesn’t return a new list. So, instead of this:
lista = list.sort(lista) # wrong: lista becomes None
You should just do this:
lista.sort() # sorts the list in place
Then you can access the elements normally:
a = lista[1] - lista[0]
Alternatively, if you need a sorted copy but don’t want to modify the original list, use sorted()
like this:
sorted_list = sorted(lista)
a = sorted_list[1] - sorted_list[0]
This will help you avoid the ‘NoneType’ object is not subscriptable error!"
I’ve faced this error before too! The problem arises because list.sort()
does not return a new sorted list. It sorts in place and returns None
. If you try to assign that None
back to your variable, that’s when Python complains that you’re trying to subscript None
. So, instead of doing this:
list = list.sort(list)
Just call:
list.sort()
This works just fine, and you can safely do:
b = list[1] - list[0]
If you need a sorted copy and don’t want to modify the original list, use:
sorted_copy = sorted(list)
b = sorted_copy[1] - sorted_copy[0]
By doing this, you’ll avoid the dreaded ‘NoneType’ object is not subscriptable error!
Hey! I’ve seen this TypeError: ‘NoneType’ object is not subscriptable pop up a few times too. It usually happens because list.sort()
doesn’t return anything, it sorts the list in place and returns None
. So when you do this:
lista = list.sort(lista)
lista
becomes None
, and trying to access lista[1]
gives you the error. The correct approach is just calling:
lista.sort()
# sorts the list in place, no assignment needed
Then you can safely access elements like:
a = lista[1] - lista[0]
If you need a sorted copy and don’t want to alter the original list, use sorted()
:
sorted_list = sorted(lista)
a = sorted_list[1] - sorted_list[0]
By doing this, you won’t encounter the ‘NoneType’ object is not subscriptable error!