I have a list and I want to sort this list and return it from the function in one line.
I tried the return of list1.sort() but the output is None and not the list1 sorted.
Is there a way to sort the list and return in one line?
Use sorted.
>>>x = ["c","b","1"]
>>>sorted(x)
["1","b","c"]
x.sort() should return None, since that is how method sort works. Using x.sort() will sort x, but it doesn't return anything.
For more ways to sort look here.
usually you would say
sorted(list1) # returns a new list that is a sorted version of list1
But sometimes you the sort to be in-place because other things are referencing that list
list1.sort() returns None, so your options are
list1[:] = sorted(list1) # still makes a temporary list though
or
sorted(list1) or list1 # always ends up evaluating to list1 since None is Falsey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With