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]
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.
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]
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.