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

Is it possible to show a console in a Jupyter notebook?
Merging dictionaries
Access matplotlib objects of scatter plot
How to run custom django-admin manage.py command
How to exclude zeros from a list
Python: Parallelize for loop reading lines from file
Python find out if a folder exists
Python Order of Operations - Addition and subtraction
Python Beautifulsoup: Unable to select element despite of it's there
Google news crawler to return results with url,title and briefing
Getting specific data values out of a dataframe - python pandas
Django import issue in Pycharm
Why is this concatenation of the float values in pandas dataframe is giving NaN output?
windows7 python36: how send to gdrive using righ click context menu?
Switch between content on TKinter / Python
PhantomJS session to Chrome/Firefox session

Categories

HOME
json
sidekiq
crate
rotation
windows-7
facebook-graph-api
memory-leaks
wms
data-science-experience
avl-tree
lotus-notes
hosts
iso
dryioc
rebol2
cross-platform
tree-traversal
vs2017
cruisecontrol.net
countif
nsmenuitem
multiplayer
bcrypt
auditing
croppic
metadata-extractor
data-conversion
pitest
pep8-assembly
percentage
entity-system
preg-grep
canvasjs
getline
pmwiki
declare
agent
visualstudio.testtools
restful-url
rule
intellilock
datalog
intersystems-ensemble
maintenance
tcserver
fontconfig
addin-express
redux-router
barcode-printing
boost-hana
project-online
gradle-release-plugin
post-processing
flexjson
fortran90
cmocka
loopj
approval-tests
galaxy
matcaffe
wif
pgm
git-checkout
httpie
guzzle6
code-first-migrations
android-search
c++-actor-framework
viewflipper
ibmsbt
hidden-field
vcl
google-admin-audit-api
ember-addon
coin-flipping
opensocial
uipickerviewcontroller
wic
opendata
bfd
real-time-updates
bigint
ftp4j
carddav
shortcuts
fieldset
crocodoc
expression-evaluation
gjs
django-nose
opengl-es-lighting
dcpu-16
port-scanning
chatroom
msn
querypath
idictionary
rtsp-client
filetime
usability-testing
gears
msf
web-analytics-tools
ajaxpro

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