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

Centralized Django Installations with VirtualEnv
Matplotlib - Draw points that satisfy condition
Lektor Pagination - TemplateSyntaxError: Encountered unknown tag 'endblock'
Can anyone help me out with the ASCII part please
Compare two databases for any differences
string to float error
python3 sending serial data to Nextion Display
Probablistic graphical model Error while fitting the model
Unable to unzip using python zipfile module
Sqlite python - attempt to write a read only database
How to choose or assign variable in django template?
How can I return to the top of the script in python?
Python Multiprocessing Process seems to stop before doing anything
Python: anonymous variable for part of the return value of a function
2-d array using Python's array.array module?
Django help_text line length convention

Categories

HOME
json
caching
crystal-reports
sidekiq
ocaml
ubuntu-16.04
reportportal
otrs
computer-vision
windows-store-apps
apollo
vlc
terrain
slim-3
click
abcpdf
dlib
ios10.3
statusbar
cocoa-touch
myob
pdfsharp
bus-error
pygooglechart
gpib
encase
helix-3d-toolkit
canvasjs
pox
xen
office365connectors
codesys
brute-force
restful-url
web-development-server
distributed-transactions
datalog
upsert
spell-checking
cgcontext
modelattribute
visual-studio-templates
settimeout
pdflib
libreadline
backstop.js
gitweb
brython
nssplitview
bluesnap
test-class
lemoon
site-prism
rad
leadtools-sdk
crash-dumps
swift2.1
git-checkout
adodb
temp-tables
node-imagemagick
dto
yahoo-boss-api
coin-flipping
config-files
visualstatemanager
pyjade
osx-snow-leopard
vmware-server
google-closure-library
client-side-scripting
digital-design
client-library
linkedhashset
blockingqueue
expression-evaluation
text-services-framework
separation-of-concerns
selectonemenu
easygui
windows-live-id
noir
grooveshark
code-design
scatterview
winsnmp
usergroups

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