0

This is my code

[temp.append(i.get_hot_post(3)) for i in node_list]
[hot_posts+i.sort(key=sort_by_rate) for i in temp ]

get_hot_posts() return a list of 3 items this way

return recent_posts[0:amount-1]

it could be that the list is shorter than 3 elements and it probably mess the things around but go on

[temp.append(i.get_hot_post(3)) for i in node_list]

after this command, in "temp" i have a list of lists and it's fine.

But when it executes

[hot_posts+i.sort(key=sort_by_rate) for i in temp ]

it gives this error

TypeError: can only concatenate list (not "NoneType") to list
Chobeat
  • 3,445
  • 6
  • 41
  • 59
  • The answers below are good, here is documentation on [List Comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) – hjweide Aug 22 '12 at 19:43

2 Answers2

4

List method sort returns None (just changing list). You can use sorted() function instead.

PS.

[temp.append(i.get_hot_post(3)) for i in node_list]

is not very good idea, cause you will have a list of None. Possible variants:

temp += [i.get_hot_post(3) for i in node_list]

or even

from operator import methodcaller 
temp += map(methodcaller(get_hot_post, 3), node_list)
Alexey Kachayev
  • 6,106
  • 27
  • 24
3

I think you meant sorted(i), no? i.sort() does the sorting in-place and returns nothing.

Also, why would you like to do [hot_posts + ...]? This will not store the values in the hot_posts, so the operation is meaningless, unless you assign the result to a new variable.

I suspect you wanted to do something like

temp = [i.get_hot_post(3) for i in node_list]
hot_posts = [sorted(i, key=sort_by_rate) for i in temp]

Although I have no idea what your last line is supposed to do. Now it just sorts each of these small lists of three and that's it.

Qnan
  • 3,714
  • 18
  • 15
  • It is supposed to concatenate all the elements in the list hot_posts. Thanks for the advice on sort(), it's the first time i use it. – Chobeat Aug 22 '12 at 20:25
  • then i think it should look like this: [post for i in temp for post in i], see http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – Qnan Aug 22 '12 at 22:56