posts = []
rows = [('02.02', 'title2', 'text2', 15, 1), ('01.02', 'title', 'text', 16, 1)]
rows = rows.sort(key=lambda x:x[3])
for i in range(2):
posts.append(rows[i])
print(posts)
Why that code returns None and how can I fix it?
>Solution :
Instead of
rows = rows.sort(key=lambda x:x[3])
You want:
rows.sort(key=lambda x:x[3])
Because the .sort() will automatically update rows without the need to reassign like so:
posts = []
rows = [('02.02', 'title2', 'text2', 15, 1), ('01.02', 'title', 'text', 16, 1)]
rows.sort(key=lambda x:x[3]) #notice the change here
for i in range(2):
posts.append(rows[i])
print(posts)
Output:
[('02.02', 'title2', 'text2', 15, 1), ('01.02', 'title', 'text', 16, 1)]
The .sort() function updates rows, but returns None.