NoneType object not iterable

T

tom

Hi!
My code is
> db = {}
>
def display():
keyList = db.keys()
sortedList = keyList.sort()
for name in sortedList:
line = 'Name: %s, Number: %s' % (name, db[name])
print line.replace('\r', '')

And it gives following error:
for name in sortedList:
TypeError: 'NoneType' object is not iterable

How can sortedList variable turn into NoneType? I just don't get it...
 
S

Stargaming

Hi!
My code is
def display():
keyList = db.keys()
sortedList = keyList.sort()
for name in sortedList:
line = 'Name: %s, Number: %s' % (name, db[name])
print line.replace('\r', '')


And it gives following error:
for name in sortedList:
TypeError: 'NoneType' object is not iterable


How can sortedList variable turn into NoneType? I just don't get it...

It does not turn into something. The `sort()` method just works "in
place", i. e. it will mutate the list it has been called with. It
returns None (because there is no other sensible return value).

For you, that means: You don't have to distinguish between keyList and
sortedList. Just call ``.sort()`` on keyList and it will just work.

HTH,
Stargaming

P.S. same information is in the docs:
http://docs.python.org/lib/typesseq-mutable.html
 
D

Daniel

Hi!
My code is
db = {}

def display():
keyList = db.keys()
sortedList = keyList.sort()
for name in sortedList:
line = 'Name: %s, Number: %s' % (name, db[name])
print line.replace('\r', '')

And it gives following error:
for name in sortedList:
TypeError: 'NoneType' object is not iterable

How can sortedList variable turn into NoneType? I just don't get it...

db is out of scope, you have to pass it to the function:
def display(db):
keyList = db.keys()
sortedList = keyList.sort()
for name in sortedList:
line = 'Name: %s, Number: %s' % (name, db[name])
print line.replace('\r', '')
 
P

Paul Rubin

Stargaming said:
It does not turn into something. The `sort()` method just works "in
place", i. e. it will mutate the list it has been called with. It
returns None (because there is no other sensible return value).

For you, that means: You don't have to distinguish between keyList and
sortedList. Just call ``.sort()`` on keyList and it will just work.

Alternatively, use
sortedList = sorted(keyList)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top