4

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?

4
  • 7
    There's a builtin function for that ... sorted ...
    – mgilson
    Nov 25, 2013 at 22:37
  • Why is this being voted to close for not demonstrating a minimal understanding? The question stated the code used, the actual return value, and the expected return value, and stated a clear question. It's evident that there's at least a minimal understanding of the problem here. Nov 25, 2013 at 22:43
  • Why the requirement that it be one line? Granted, that require is easily satisfied in this case, but still ... are you playing code golf?
    – Robᵩ
    Nov 25, 2013 at 22:50
  • @WaleedKhan, but there is a subtle difference between sorting a list and returning a sorted version of the list Nov 25, 2013 at 22:55

3 Answers 3

8

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.

1
  • 2
    If you want to improve your answer, you could point out to OP why list1.sort() should return None by normal python conventions.
    – mgilson
    Nov 25, 2013 at 22:45
2

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
1
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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.