Skip to content Skip to sidebar Skip to footer

Sorting A List Comprehension In One Statement

I noticed something I didn't expect when writing a script this morning. I tried to use a list comprehension and sort it all in one statement and got a surprising result. The follow

Solution 1:

The method list.sort() is sorting the list in place, and as all mutating methods it returns None. Use the built-in function sorted() to return a new sorted list.

result = sorted((trans for trans in my_list if trans.type in types),
                key=lambda x: x.code)

Instead of lambda x: x.code, you could also use the slightly faster operator.attrgetter("code").

Solution 2:

Calling .sort on a list returns None. It makes perfect sense that this result is then assigned to result.

In other words, you create a list anonymously with a list comprehension, then call .sort, and the list is lost while the result of the .sort call is stored in the result variable.

As others have said, you should use the sorted() builtin function in order to return a list. (sorted() returns a sorted copy of the list.)

Solution 3:

you want the sorted builtin function. The sort method sorts a list in place and returns None.

result = sorted([trans for trans in my_list if trans.typein types],key = lambda x: x.code)

this could be done slightly better by:

importoperator
result = sorted( (trans for trans in my_list if trans.type in types ), key=operator.attrgetter("code"))

Post a Comment for "Sorting A List Comprehension In One Statement"