user2999009
user2999009

Reputation: 103

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?

Upvotes: 5

Views: 8467

Answers (3)

yozn
yozn

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

John La Rooy
John La Rooy

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

user2961646
user2961646

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

Related Questions