Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 following code summarizes my general use case, but is simplified for this question:

Transaction = namedtuple('Transaction', ['code', 'type'])  my_list = [Transaction('code1', 'AAAAA'), Transaction('code2', 'BBBBB'), Transaction('code3', 'AAAAA')]  types = ['AAAAA', 'CCCCC']  result = [trans for trans in my_list if trans.type in types].sort(key = lambda x: x.code)  print result 

Output:

None 

If I create the list using the comprehension, then sort it after the fact, everything is fine. I'm curious why this happens?

like image 840
donopj2 Avatar asked Jul 11 '12 13:07

donopj2


People also ask

Can you nest list comprehensions?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.

Does list comprehension preserve order?

Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result.


Video Answer


2 Answers

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").

like image 120
Sven Marnach Avatar answered Oct 04 '22 04:10

Sven Marnach


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.)

like image 36
Platinum Azure Avatar answered Oct 04 '22 03:10

Platinum Azure