python


Pythonic way to subtract one list from another with validation of presence


A good pythonic way to subtract one list from another is to use list comprehension:
# remove all elements of list2 from list1
list1 = [x for x in list1 if x not in list2]
How would I, in the same step, validate that each x actually occurs in list1 (e.g. in order to raise an error on missing elements)?
You don't need to check. x by definition has to be in list1, or else the iterator wouldn't provide it (since you're iterating over list1's items)
But in case it might get modified while you're iterating (which is a case you should definitely avoid):
list1 = [x for x in list1 if x not in list2 and x in list1]
If you need more complex behaviour like showing an error message, use an explicit loop
list_delta = []
for x in list1:
if x not in list1:
raise IndexError("oh god what")
if x not in list2:
list_delta.append(x)
But honestly this seems like an X-Y problem because you should never have to do this to begin with.
I'm not sure I understand what you're asking there, but if the order doesn't matter and there are no repetitions, you can use set difference as #Chih-Hsu Jack Lin mentioned in the comments:
list(set(list1) - set(list2))
And if order doesn't matter, but element count does matter, another approach is to use collections.Counter:
list((Counter(list1) - Counter(list2)).elements())

Related Links

Accessing django oscar product attributes
Incorrectly Replacing Content
Python Max Recursion Depth
Error loading IPython notebook
Accessing Python webserver remotely on Amazon EC2
Efficient combined in-place adding/removing of rows of a huge 2D numpy array
PANDAS: fast check whether integers fall into a set of intervals
python hex-editor binary change
Out of Memory with MultiPart Post, Python 2.7
How to ignore objects that don't satisfy the “class” conditions?
SaltStack client.cmd outputter
Confused about try/except with custom Exception
Url fetches in google appengine live
django hyperlink in custoom middleware not workiing
cx_Freeze - module is included on freeze, but not used properly
How to stop a while loop in an imported module using a button

Categories

HOME
openssl
websphere
visual-studio-2013
youtube-livestreaming-api
wms
mapbox-gl-js
survival-analysis
specflow
checksum
rebol
browserify
eval
packer
oclint
symfony2-easyadmin
rapidjson
riak
cairo
vs2017
attask
tweets
plsqldeveloper
raphael
embedly
cocoa-touch
bootstrap-typeahead
pdfsharp
python-textprocessing
opencart2.3
nesc
hana-studio
positioning
superagent
hibernate-cache
exponential
backup-strategies
canvasjs
mmdrawercontroller
jboss-esb
es-shell
axis-labels
sql-like
fltk
jquery-multidatespicker
lexical-analysis
nsexception
code-composer
productivity
intersystems-ensemble
homekit
crop
mod-fcgid
rich-text-editor
archer
timesten
tuleap
defold
chunked-encoding
amazon-machine-learning
tiddlywiki
greenhills
redux-router
lotus
rxvt
shinyjs
restivejs
createobject
sqldatareader
inject
debugdiag
pydio
slam-algorithm
com-interop
distribute
affix
application-loader
mirrorlink
python-winshell
paypal-nvp
mptcp
team-build
pyopengl
graphical-logo
web-component-tester
word-2013
pisa
pgagent
scala-2.11
ibmsbt
java-collections-api
csplit
unison
wic
nservicebus4
va-list
soa-suite
magickwand
wpdb
marmalade-edk
dropdownlistfor
attachevent
crocodoc
caliper
legacy-code
adsl
msn
asp.net-routing
task-management
file-encodings
visual-c++-2008-express
filetime
graph-layout

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App