TypeError: NoneType object not iterable

Question:

It might be silly question but I just started to learn OOP in Python and I am struggling to get this one:

The following code works fine:

class Name(object):
    def __init__(self):
        self.name=None

C1='Stephen Curry'
C2='Kevin Durant'
C3='LeBron James'
C4='Chris Paul'


nameList=[C1,C2,C3,C4]
nameList.sort()
for e in nameList:
    print (e)

However, when I use nameList.sort() inside the for loop, it gives me “TypeError: ‘NoneType’ object is not iterable”

class Name(object):
    def __init__(self):
        self.name=None

C1='Stephen Curry'
C2='Kevin Durant'
C3='LeBron James'
C4='Chris Paul'

nameList=[C1,C2,C3,C4]

for e in nameList.sort():
    print (e)

Thanks

Asked By: A.E

||

Answers:

sort returns None because it sorts the list in place. If you want to iterate over a sorted list in one statement, you should use sorted:

for e in sorted(nameList):
    pass
Answered By: brianpck
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.