TypeError: object of type 'NoneType' has no len() in Python

Dung Do Tien Aug 29 2021 205

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() # Sort by alphabet ascending
for n in range(len(students)):
    print(students[n])

But I get an exception TypeError: object of type 'NoneType' has no len() when I run code above.

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    for n in range(len(students)):
TypeError: object of type 'NoneType' has no len()

I am using Python 3.8.2

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

Thanks for any response.

Have 1 answer(s) found.
  • S

    Samuel Kiseve Aug 29 2021

    This error throw because students variable is not an array, it's an object so it does not support len() method.

    You are wrong about using the sort() method. Please change students = students.sort() to students.sort(). See an example below:

    students = ["Hannah", "Anna", "Trump Hazon", "Jonh Buddy", "Red Bull"]
    students.sort()
    for n in range(len(students)):
        print(students[n])

    #OUTPUT

    Anna
    Hannah
    Jonh Buddy
    Red Bull
    Trump Hazon

    Hope it's useful for you.

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