Sorted_swap none

Screen Link:

https://app.dataquest.io/m/356/guided-project%3A-exploring-hacker-news-posts/7/sorting-and-printing-values-from-a-list-of-lists

My Code:

swap_avg_by_hour = []
x = row[0]
y = row[1]

for x, y in avg_by_hour:
    x, y = y, x
    swap_avg_by_hour.append([x, y])
    sorted_swap = swap_avg_by_hour.sort(reverse=True)

print(swap_avg_by_hour)
print("\n")
print(sorted_swap)```

What I expected to happen:

[[38.59, '15'], [23.81, '02'], [21.52, '20'], [16.8, '16'], [16.01, '21'], [14.74, '13'], [13.44, '10'], [13.23, '14'], [13.2, '18'], [11.46, '17'], [11.38, '01'], [11.05, '11'], [10.8, '19'], [10.25, '08'], [10.09, '05'], [9.41, '12'], [9.02, '06'], [8.13, '00'], [7.99, '23'], [7.85, '07'], [7.8, '03'], [7.17, '04'], [6.75, '22'], [5.58, '09']]

What actually happened: 

None


<!--Enter other details below: -->

I get the correct answer but I get it in swap_avg_by_hour and not sorted_swap.
1 Like

Hello @davidgarber,

The reason you don’t get the correct answer in sorted_swap is that when you use the sort() method as used in your code above: sorted_swap = swap_avg_by_hour.sort(reverse=True) , the sort() method doesn’t return any value.

Alternatively, you can also use Python’s in-built function sorted() which returns a sorted list as shown in this line of code: sorted_swap = sorted(swap_avg_by_hour, reverse=True)

I hope this helps.

That is because sorted_swap is a lists of lists. You can can use the key parameter to specify the position of the sublists that you want the main list to be sorted by. Notice that this parameter takes in a function, not an int.

 sorted_swap = swap_avg_by_hour.sort(key=lambda x: x[0], reverse=True)
 

Thank you. I really appreciate your help.

1 Like