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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With