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

Python Cutting a string on a certain point
Ansible become_user error UnicodeEncodeError: 'ascii' codec can't encode character
Dynamic way to create new columns as a function of existing columns in pandas
polymorphic dispatch: distinguishing Python integers vs. floating-point numbers vs. strings
HTCondor output files: obtain created directory
getting select values with flask [duplicate]
Tensorflow tf.matmul example is incorrect?
drawing flower with python turtle
Python while loop iteration does not work
Rows not displaying properly in Tkinter GUI
Getting InvalidArgumentError in Tensorflow
Django - 2 URLS with same regex, but different variables and views
Parse headers with urllib2 if there is a duplicate [duplicate]
Python histogram outline
python IDLE changing default open file location to u C:\Users\user\documents
PyQt5 virtual keyboard (TypeError: missing 1 required positional argument)

Categories

HOME
makefile
json
openssl
boost-thread
thunderbird-addon
google-sheets-api
extract
hana
ubuntu-12.04
phonegap-cli
propertygrid
android-viewpager
typeahead
apache-karaf
ng-show
internet-explorer-8
google-maps-android-api-2
apply
data-cleansing
visual-c++-2017
rhandsontable
maximo
edge-detection
ggmap
pep8-assembly
jackson-dataformat-csv
encase
getjson
twitter-bootstrap-2
entity-system
clockwork
picturebox
pycparser
nsurlconnection
powershell-remoting
css-counter
color-scheme
image-compression
meta-raspberrypi
agent
alchemy.js
common.logging
cgo
nsexception
mediawiki-extensions
knockout-3.0
paho
3scale
dojox.grid.datagrid
livescribe
spell-checking
communication-protocol
ingres
libtiff.net
xib
audioqueue
software-product-lines
try-finally
ng2-material
scriptlet
dac
loopj
license-key
site-prism
datasnap
registrykey
graphical-logo
apache-mina
uos
low-level
inputaccessoryview
microblaze
node-inspector
slick-2.0
help-viewer
flash-cc
bignum
bigint
appfog
icsharpcode
fotoware
shim
objective-c-protocol
makefile-project
coff
post-redirect-get
libavformat
chatroom
hibernate3-maven-plugin
code-design
web-statistics
microsoft.ink
internals

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