Python Anonymous Object not Created?

Question:

This is working well –

mydict = {...some data...}
another = mydict.keys()
another.sort(key=sort_key, reverse=True)
for v in another:...

while this isn’t –

for v in mydict.keys().sort(key=sort_key, reverse=True):...

throws

TypeError: 'NoneType' object is not iterable

Why?

Asked By: GuyC

||

Answers:

list.sort will return you None.

Variable list is dict in your example
Means list.keys() is list data type and list.sort will give sorted list itself. But return None

>>> list = {1:1, 2:2}
>>> list.keys()
[1, 2]
>>> list.keys().sort()
>>> b = list.keys().sort()
>>> b
>>> print b
None

When you try to iterate over none

>>> [x for x in list.keys().sort()]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

It gives error

Answered By: Nilesh
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.