Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python How sort list in one line and return it

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?

like image 710
user2999009 Avatar asked Dec 19 '22 21:12

user2999009


2 Answers

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.

like image 173
AHuman Avatar answered Dec 30 '22 10:12

AHuman


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
like image 45
John La Rooy Avatar answered Dec 30 '22 11:12

John La Rooy