Remove elements larger than a specific value Using enum()
In this code, we use the enumerate() function to loop over the index and element of the num_list. Then, we filter the numbers using list comprehension just like before. The enumerate() function provides an elegant way to loop over the index and element of a list simultaneously, and it can help to make the code more readable.
Python3
num_list = [ 30 , 200 , 65 , 88 , 98 , 500 , 34 ] # using enumerate() to loop over index and element num_list = [num for i, num in enumerate (num_list) if num < = 100 ] # display the list print (num_list) #This code is contributed by Vinay Pinjala. |
[30, 65, 88, 98, 34]
The time complexity of the code is O(n) as the list comprehension and enumeration loop both iterate over the entire list once, where n is the length of the input list.
The auxiliary space is also O(n) as a new list is created to store the filtered elements, which can be at most the size of the original list.
RECOMMENDED ARTICLES – Remove the given element from the list
Remove elements larger than a specific value from a list in Python
In this article, we will learn to remove elements from a list that is larger than a specific value in Python.
Example
Input: [12, 33, 10, 20, 25], value = 21
Output: [12, 10, 20]
Explanation: Removed all element from the list that are greater than 21.