In short, this is the plan: I want to remove the smallest value from a Python list. My approach to that was creating a new list trimmed
, which is basically a copy of the original one but with a condition like:
add it to trimmed only if the value is not equal to min(). Like this:
lis=[]
trimmed =[]
n = int(input("Enter number of elements : "))
for i in range(0, n):
elements = int(input("Type a number: "))
lis.append(elements) # adding the elements
# "trimmed" appends a new copy of "lis" removing the smaller value
trimmed = [x for i,x in enumerate(lis) if i != min(lis)]
print(trimmed)
The problem is, it sometimes seems to build trimmed
by removing a value in a specific index rather than removing the actual smaller one. E.g. I have just inputted 5 ,2 ,6 and 9. It should ramv removed number two. Instead, it prints out [5, 2, 9]
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]