85.2k views
4 votes
write a python function that takes the largest and smallest numbers in a list, and swap them (without using min() or max() )

User Pbuck
by
5.6k points

1 Answer

2 votes

Answer:

def SwapMinMax ( myList ):

myList.sort()

myList[0], myList[len(myList)-1] = myList[len(myList)-1], myList[0]

return myList

Step-by-step explanation:

By sorting the list, you ensure the smallest element will be in the initial position in the list and the largest element will be in the final position of the list.

Using the len method on the list, we can get the length of the list, and we need to subtract 1 to get the maximum element index of the list. Then we simply swap index 0 and the maximum index of the list.

Finally, we return the new sorted list that has swapped the positions of the lowest and highest element values.

Cheers.

User Dason
by
5.5k points