How to delete elements smaller than a specific value from a list in Python

Hello folks, today we are going to learn how to delete elements smaller than a given value from a list in Python.

Deleting elements smaller than a specific value from a list in Python

Let us consider a list arr and a value k:

arr = [1 ,2 ,3, 56 ,89 ,77 ,44 ,5 ,888 ,663 ]

k = 8

Our goal is to remove all elements from the list arr whose value is less than k.

remove() –¬†This method takes a value as a parameter. It deletes the first element whose value is the same as that of given parameter.

Learn more about remove() and other methods to delete an element from a list 

Code:

def delete_less_than_k(arr,k):
  temp = [] #Temporary list
  for val in arr:#Iterating the list arr

    if val<k:
      temp.append(val)
  #All the elements whose value is less than k are stored in temp
  for i in temp:#Iterating the temporary list
    arr.remove(i)
  

arr = [1 ,2 ,3, 56 ,89 ,77 ,44 ,5 ,888 ,663 ]
k = 8
delete_less_than_k(arr,k)#Call the function
print(arr)

Output:

[56, 89, 77, 44, 888, 663]

Leave a Reply

Your email address will not be published.