Remove Max and Min values from python list of integers
Here's another way to do it if you don't want to change the order of the items:
mylist = [1, 4, 0, 3, 2]
mylist.remove(max(mylist))
mylist.remove(min(mylist))
Assumes that the high/low don't have any duplicates in the list, or if there are, that it's OK to remove only one of them.
This will need to do 2-4 passes through the list: two to find the max and min values, and up to 2 to find the values to remove (if they both happen to be at the end of the list). You could reduce this to one by writing a Python loop to find the max and min in a single pass (and remember the index of each so you can delete the items by index after the loop). However, min()
and max()
are implemented in C, so replacing them with Python code would probably result in lower performance even if it allowed you to reduce the number of passes.
How to remove lowest elements in list?
Problem: Thou Shalt Not Modify A List During Iteration
Summary: When we remove the first element containing 19, the rest "slide down". For example, when we removed arr[2]
aka ['Varun', 19]
, ['Kakunami', 19]
replaced it. Then, the loop continued to arr[3]
which is now ['Vikas', 21]
. This, in a way, left ['Kakunami', 19]
out of the loop.
Solution: To work around this, just loop over the list from the reverse order: (Have to use a while
...I think)
arr=[['Harsh', 20], ['Beria', 20], ['Varun', 19], ['Kakunami', 19], ['Vikas', 21]]
arr.sort(key=lambda x: (x[1],x[0]))
min_value=min(arr,key=lambda x:x[1])
min_marks=min_value[1]
i = len(arr) - 1;
while i >= 0:
if arr[i][1]==min_marks:
arr.remove(arr[i])
i = i - 1
print arr
A repl.it as a demo
You could do this recursively:
arr=[['Harsh', 20], ['Beria', 20], ['Varun', 19], ['Kakunami', 19], ['Vikas', 21]]
arr.sort(key=lambda x: (x[1],x[0]))
min_value=min(arr,key=lambda x:x[1])
min_marks=min_value[1]
def removeLowest(arr, min):
for i in arr:
if i[1]==min_marks:
arr.remove(i)
return removeLowest(arr, min)
return arr
removeLowest(arr, min)
print arr
Otherwise, there are many other alternatives :)
Remove the smallest value in a list python question
Take a copy of the input list then:
def remove_smallest(numbers):
if numbers is None or len(numbers) == 0:
return []
copy = numbers.copy()
copy.remove(min(numbers))
return copy
print(remove_smallest([1,0,0,1]))
output:
[1, 0, 1]
Alternative:
def remove_smallest(numbers):
if numbers is None or len(numbers) == 0:
return []
i = numbers.index(min(numbers))
return numbers[:i] + numbers[i+1:]
Removing the lowest numbers from a list
list.remove
deletes the first matched value in the list. In order to remove all occurrences of the current lowest number, you'll have to call it list.count(min(list))
times.
Here's the function that removes n
smallest numbers from lst
and that doesn't involve list.remove
:
def remove_n_smallest(lst, n):
for _ in range(n):
m = min(lst)
lst[:] = (x for x in lst if x != m)
And here's the example for lst
from your question:
>>> remove_n_smallest(lst, 2)
>>> lst
[100]
>>> sum(lst) / len(lst)
100.0
Removing the smaller value from a list using function min()
It's because your if i != min(lis)
checks the minimum value against the index variable i
instead of the value itself x
. enumerate
gives back (index, val)
pairs i.e, (i, x)
here. It happened that min(lis)
was 2, so whenever i
hits 2, that value will be trimmed, hence you saw 6 disappearing (which was at 2nd index). Fix is to compare against x
:
trimmed = [x for i,x in enumerate(lis) if x != min(lis)]
should do.
But better yet, let us compute the minimum only once (above computes many times):
minimum = min(lis)
trimmed = [x for i,x in enumerate(lis) if x != minimum]
and further, you don't seem to need i
at all:
minimum = min(lis)
trimmed = [x for x in list if x != minimum]
dropping the lowest values from a list
You don't require to reverse sort and find the smallest element. Use min
on list l
which returns the smallest value from l
and remove using l.remove
conveniently.
import math
l = [1,5,6,72,3,4,9,11,3,8]
def drop(k):
while len(l)!=0 and k > 0:
k = k - 1
l.remove(min(l))
return l
k = math.ceil(len(l) * 0.25)
print(drop (k))
# [5, 6, 72, 4, 9, 11, 8]
Related Topics
Sqlalchemy: How to Filter Date Field
Numpy: Checking If a Value Is Nat
Split Datetime Column into a Date and Time Python
Cast String to Float Is Not Supported in Linear Model
Most Efficient Way to Forward-Fill Nan Values in Numpy Array
Calculate Final Letter Grade in Python Given 4 Test Scores
Sklearn Error Valueerror: Input Contains Nan, Infinity or a Value Too Large for Dtype('Float64')
Get All Rows That Have Same Value in Pandas
Is There a Memory Efficient and Fast Way to Load Big Json Files
Collecting and Reporting Pytest Results
How to Find the Maximum Consecutive Occurrences of a Number in Python
Get Rid of Columns With Null Value in Json Output
Using Pyserial to Send Binary Data
Python: Searching for Common Values in Two Files
How to Download Multiple Files or an Entire Folder from Google Colab
How to Change the File Name of an Uploaded File in Django
Python3: Typeerror: List Indices Must Be Integers or Slices, Not Str
Running Command With Paramiko Exec_Command Causes Process to Sleep Before Finishing