Reputation: 103
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?
Upvotes: 5
Views: 8467
Reputation: 411
list1 = [6, 7, 4, 23, 10, 79]
list2 = [list1.pop(list1.index(min(list1))) for i in range(len(list1))]
print(list2)
Output:
[4, 6, 7, 10, 23, 79]
Upvotes: 1
Reputation: 304255
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
Upvotes: 2
Reputation:
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.
Upvotes: 9