BaguetteYeeter
BaguetteYeeter

Reputation: 81

How to sort a list into values closes to 0

I have a list that is myList = [1, 3, 5, 2.5, -3, -0.5]

How would I sort the list so that I would get [-0.5, 1, 2.5, 3, -3, 5]

I've tried using min() but that only outputs one value, and I need a list

My code is:

>>> myList = [1, 3, 5, 2.5, -3, -0.5]
>>> sortedList = function(myList)
>>> print(sortedList)
[-0.5, 1, 2.5, 3, -3, 5]

Upvotes: 0

Views: 71

Answers (1)

Samwise
Samwise

Reputation: 71479

Sounds like you want to sort by the absolute value, which you can compute with the abs function.

>>> myList = [1, 3, 5, 2.5, -3, -0.5]
>>> sorted(myList, key=abs)
[-0.5, 1, 2.5, 3, -3, 5]

Upvotes: 5

Related Questions