Remove all elements matching a predicate from a list in-place

2024/11/15 23:28:04

How can I remove all elements matching a predicate from a list IN-PLACE?

T = TypeVar("T")def remove_if(a: list[T], predicate: Callable[[T], bool]):# TODO: Fill this in.# Test:
a = [1, 2, 3, 4, 5]
remove_if(a, lambda x: x % 2 == 0)
assert(a == [1, 3, 5])

The answer should be O(N); not O(N^2).

Here is a similar question but it does not require IN-PLACE removal: Removing an element from a list based on a predicate

In Rust this is Vec::retain(). In C++ it is std::remove_if() (plus erase()).

Is there an equivalent in Python?

Answer

This does the trick using the standard algorithm. It does unnecessarily copy elements to themselves before the first failure of the predicate, so you may want to add a find() at the start of the loop (see the "Possible Implementation" for C++'s std::remove_if()). It should still be pretty fast though and that doesn't affect the complexity which is O(N).

from typing import Callable, TypeVarT = TypeVar("T")def remove_if(lst: list[T], predicate: Callable[[T], bool]):i = 0for element in lst:if not predicate(element):lst[i] = elementi += 1del lst[i:]

Edit: @mozway's answer is a lot simpler and probably O(N) too. You would need to benchmark to see which is actually faster because his probably isn't in-place in memory terms (though it is in-place in logical terms).

a[:] = [x for x in a if x%2==0]
https://en.xdnf.cn/q/118993.html

Related Q&A

Python-scriptlines required to make upload-files from JSON-Call

Lacking experience & routine for Python-programming. Borrowing examples from forums have made a script which successfully makes a JSON-cal (to Domoticz) and generates & prints the derived JSON-…

python pygame mask collision [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.The com…

How to find max average of values by converting list of tuples to dictionary?

I want to take average for all players with same name. I wrote following code. its showing index error whats the issue?Input: l = [(Kohli, 73), (Ashwin, 33), (Kohli, 7), (Pujara, 122),(Ashwin, 90)]Out…

Cannot pass returned values from function to another function in python

My goal is to have a small program which checks if a customer is approved for a bank loan. It requires the customer to earn > 30k per year and to have atleast 2 years of experience on his/her curren…

What is the difference here that prevents this from working?

Im reading a list of customer names and using each to find an element. Before reading the list, I make can confirm this works when I hard-code the name,datarow = driver.find_element_by_xpath("//sp…

How can I extract numbers based on context of the sentence in python?

I tried using regular expressions but it doesnt do it with any context Examples:: "250 kg Oranges for Sale" "I want to sell 100kg of Onions at 100 per kg"

Chart with secondary y-axis and x-axis as dates

Im trying to create a chart in openpyxl with a secondary y-axis and an DateAxis for the x-values.For this MWE, Ive adapted the secondary axis example with the DateAxis example.from datetime import date…

Env var is defined on docker but returns None

I am working on a docker image I created using firesh/nginx-lua (The Linux distribution is Alpine): FROM firesh/nginx-luaCOPY ./nginx.conf /etc/nginx COPY ./handler.lua /etc/nginx/ COPY ./env_var_echo.…

No Browser is Open issue is coming when running the Robot framework script

I have created Test.py file which has some function in it and using those function names as Keywords in sample.robot file. Ex: - Test.pydef Launch_URL(url):driver.get(url)def article(publication): do…

How to run python file in Tkinter

Im a beginner in Python, hence the question. i would like to run a python file (smileA.py) in Tkinter. How would i start? I do not wish for it to run when clicking a button, but the file to run automa…