Move the highest value to start of list

Question:

Goal: move the highest value in list to index: 0, without re-ordering any other elements.

What is the most Pythonic way to do this?

Preferably:

  • a one-liner,
  • without imports

Example:

[0.013, 0.726, 0.22323, 5.08, 1.23432]

Desired Output:

[5.08, 0.013, 0.726, 0.22323, 1.23432]
Asked By: DanielBell99

||

Answers:

Here is a list comprehension based approach:

inp = [0.013, 0.726, 0.22323, 5.08, 1.23432]
output = [max(inp)] + [x for x in inp if x != max(inp)]
print(output)  # [5.08, 0.013, 0.726, 0.22323, 1.23432]

This builds an output list whose first element is the max value in the input list, followed by that same input list with its max value removed.

Answered By: Tim Biegeleisen
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.