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

max-Function for attributes of objects
Parsing GET request data with from SimpleHTTPServer
Save Matplotlib image to s3 without saving locally using Boto
Adding attendees with Google Calendar API
matplotlib.pyplot issue with subplot, np.ones and np.arange?
Error When Trying to Run Simple Kivy Program (Windows)
Removing items for a list using a loop in Python
Tornado render() - Too many arguments
Plotting multiple points instead of just one in Python
AttributeError: 'NavigableString' object has no attribute 'find_all' (NameError)
Join mysql tables one after the other using python
Can two celery applications be interdependent? or two tasks of one application be interdependent?
How to insert map type into cassandra using cassandra-driver for python
How to deploy Django website in cPanel? [duplicate]
re.compile does not work properly
Using Appkit and Python to hide mouse cursor on OSX

Categories

HOME
sql-server
symfony
google-contacts
jbehave
appmaker
console
urlencode
nodemailer
jframe
subquery
onenote-api
goutte
octopus-deploy
eclipse-cdt
ndis
onsen-ui2
opera-mini
device-detection
koa
rails-activerecord
prediction
jquery-form-validator
jflex
spring-data-neo4j
vcard
google-api-dotnet-client
geomesa
color-scheme
jboss-esb
soundjs
onbackpressed
knockout-3.0
tango
cppunit
seamless-immutable
broadcast
static-code-analysis
festival
payu
xib
easing
cron-task
ruby-2.0
git-annex
tuxedo
soda
mpeg-4
supportmapfragment
usb-drive
fortran90
altbeacon
difference
intellitest
divide-by-zero
gulp-livereload
swift2.1
gyroscope-framework
docopt
libssh2
yahoo-boss-api
emma
proxies
valence
picat
delphi-xe3
reserved-words
broadcasting
resource-files
visual-c++-2010-express
goinstant
appfog
tridion2009
symfony-2.0
scrollto
unions
objective-c-protocol
nintendo
tcxgrid
scraperwiki
datacontract
charts4j
posting
port-scanning
ihttphandler
ets
.app
symbol-server
google-instant
openvg
virtualquery
weborb
database-diagramming





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