7

Remove element with Maximum value in Python List

 7 months ago
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

September 12, 2023 / List, Python / By Varun

This tutorial will discuss how to remove element with maximum value in Python list.

Suppose we have a list of numbers.

Copy to clipboard
sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 89, 51]
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.

Copy to clipboard
# Find the highest number
highestNumber = max(sampleList)
# 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,

Copy to clipboard
# 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)
# 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

Copy to clipboard
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]
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK