Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a version of list.sort() that returns the sorted list?

I'm trying to perform an inline operation where I need to sort a list as part of the process. The sort function of list type objects operates on the list it was called on instead of returning the result.

The Python docs confirms this:

list.sort()
Sort the items of the list, in place.

I tried this through Python command-line and here's the result:

>>> a = list("hello").sort()
>>> print a
None
>>> b = list("hello")
>>> print b
['h', 'e', 'l', 'l', 'o']
>>> b.sort()
>>> print b
['e', 'h', 'l', 'l', 'o']

Is there a way to skip around this issue and make a line such as the following possible?

result = list(random.choice(basesalts)).sort()

Using the code above would help me reduce the length and verbosity of my code.

like image 549
Gabriele Cirulli Avatar asked Dec 02 '22 23:12

Gabriele Cirulli


1 Answers

There's the built-in sorted():

>>> a = sorted(list('hello'))
>>> a
['e', 'h', 'l', 'l', 'o']

Also notice that you don't need list() anymore:

>>> sorted('hello')
['e', 'h', 'l', 'l', 'o']

Since basesalts seems to be a list of strings, you can just do:

result = sorted(random.choice(basesalts))

If that is the kind of output you're looking for.

like image 66
Rik Poggi Avatar answered Dec 04 '22 11:12

Rik Poggi