Python Lists – Create List, Sort, and Select First in One Line – Not Possible?

Question:

Desired code:

SmallestNumber = [ 5, 7, 3 ].sort()[0]

This however does not work.

What does work:

Numbers = [ 5, 7, 3 ]
Numbers.sort()
SmallestNumber = Numbers[0]

Is there any way to do this in one line?

It seems that the issue is related to [list].sort() returning a NoneType.

It seems that the sorted() function allows me to do this:

Numbers = [ 5, 7, 3 ]
SmallestNumber = sorted( Numbers )[0]

This would work for me but I would prefer to accomplish this with a single line if possible.

Asked By: Alex

||

Answers:

SmallestNumber = sorted([ 5, 7, 3 ])[0]
Answered By: Dmitry Erohin

For more simplicity try builtin function:

min([ 5, 7, 3 ])

3

Answered By: Sarim Bin Waseem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.