Removal of elements in list can be performed using many inbuilt functions. Removing all or just a single occurrence removal both functions are present in Python library. This article discusses to remove just the first K occurrences of elements matching particular condition.
Method #1: Naive Method We can append the elements that are matching condition after K occurrences of elements have been done and hence would perform the task similar to the removal.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 , 8 , 5 ]
print ("The original list is : " + str (test_list))
counter = 1
res = []
for i in test_list:
if counter > 4 or not (i % 2 ! = 0 ):
res.append(i)
else :
counter + = 1
print ("The filtered list is : " + str (res))
|
Output:
The original list is : [3, 5, 1, 6, 7, 9, 8, 5]
The filtered list is : [6, 9, 8, 5]
Time Complexity: O(n)
Space Compelxity: O(n)
Method #2: Using itertools.filterfalse() + itertools.count() This is different and elegant way to perform this particular task. It filters out all the numbers that become greater than K as counter reaches K and matches against the condition. This is one-liner and preferred method to achieve this task.
Python3
from itertools import filterfalse, count
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 , 8 , 5 ]
print ("The original list is : " + str (test_list))
res = filterfalse( lambda i, counter = count(): i % 2 ! = 0 and
next (counter) < 4 , test_list)
print ("The filtered list is : " + str ( list (res)))
|
Output:
The original list is : [3, 5, 1, 6, 7, 9, 8, 5]
The filtered list is : [6, 9, 8, 5]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #3: Use the filter() function and lambda function.
Step-by-step approach:
- Define a lambda function to check if an element is odd.
- Use the filter() function to filter out the first K elements that match the condition using the lambda function.
- Convert the filtered object returned by the filter() function to a list and return it.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 , 8 , 5 ]
print ( "The original list is : " + str (test_list))
K = 4
counter = K
def filter_func(x):
global counter
if x % 2 ! = 0 :
counter - = 1
return counter < 0
else :
return True
res = list ( filter (filter_func, test_list))
print ( "The filtered list is : " + str (res))
|
Output
The original list is : [3, 5, 1, 6, 7, 9, 8, 5]
The filtered list is : [6, 9, 8, 5]
Time complexity: O(n) as we are iterating over the list once.
Auxiliary space: O(n) as we are creating a new list to store the filtered elements.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
15 May, 2023
Like Article
Save Article