TypeError: 'NoneType' object is not subscriptable in Python

Dung Do Tien Aug 30 2021 37

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have a small assignment, I have an array of name students and I want to order them by alphabet ascending. Like this:

students = ["Hannah", "Anna", "Trump Hazon", "Jonh Buddy", "Red Bull"]
students = students.sort()

print(students[0])
print(students[1])
print(students[2])

But I get an exception TypeError: 'NoneType' object is not subscriptable when I am trying to run code above.

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(students[1])
TypeError: 'NoneType' object is not subscriptable

I'm using Python version 3.8.2.

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • G

    Gulam Aug 30 2021

    The error TypeError: 'NoneType' object is not subscriptable throw when your variable is an object but you access it as an array. 

    So to sort an array you can change students = students.sort() to  students.sort(). See an example below:

    students = ["Hannah", "Anna", "Trump Hazon", "Jonh Buddy", "Red Bull"]
    students.sort()
    
    print(students[0])
    print(students[1])
    print(students[2])

    #OUTPUT

    Anna
    Hannah
    Jonh Buddy
    
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close