Remove element with Maximum value in Python List
source link: https://thispointer.com/remove-element-with-maximum-value-in-python-list/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Remove element with Maximum value in Python List
This tutorial will discuss how to remove element with maximum value in Python list.
Suppose we have a list of numbers.
sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 89, 51]
If we want to remove the element with the maximum value from this list, we first need to identify the highest number. We can achieve this by passing the list to the max() function, which will return the highest number in the list.
# Find the highest number highestNumber = max(sampleList)
Subsequently, by calling the remove() method of the list and passing this number as an argument, we can remove the highest value. It’s important to note that the remove method will delete only the first occurrence of the value in the list. If we want to remove all occurrences of the maximum number from the list, we will need to call the remove() method in a loop until the number is no longer present in the list.
Let’s see the complete example,
# A List of Numbers sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 89, 51] print("Original List:", sampleList) # Find the highest number highestNumber = max(sampleList) while highestNumber in sampleList: # Remove the highest number in List sampleList.remove(highestNumber) print("List after removing the highest number:") print(sampleList)
Output
Original List: [45, 67, 22, 45, 22, 89, 71, 22, 89, 51] List after removing the highest number: [45, 67, 22, 45, 22, 71, 22, 51]
Summary
Today, we learned how to remove element with maximum value in Python list.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK