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

Mqtt subscribe message while continuous publishing to topic
flask-restless validation_exceptions not working for few column in flask-sqlalchemy models
I don't understand how cache work's on GAE python
Get first version of a line with duplicate values versus one column
Using set()/setp() to set unknown properties in matplotlib
Is there a built-in Python function which will return the first True-ish value when mapping a function over an iterable?
Check if some text exists on the webpage using getPageSource. I get error Object has no attribute getPageSource
Detect if connected to the internet using a tethered phone in Python
Sorting a list of list of tuples
Efficient concatenation of byte data in python without creating a huge list?
django two digit integer in choice field
add number to all elements of a list within a class?
Django : how could I overload Q in django.db.models.query QuerySet to use for a special purpose in my Manager
Python Paramiko - Determine what ciphers and key-exchange algorithms are available
Python: Element assignment in a scipy.sparse.diags matrix
How to include a variable name inside a variable name? [duplicate]

Categories

HOME
google-cloud-bigtable
redis
shopify
puzzle
jar
system-verilog
wildcard
performancecounter
raspbian
fparsec
steam
command
rocketmq
orientation
quill
apiconnect
browserify
jframe
wordpress-theming
game-maker-studio-1.4
jquery-terminal
multicore
jive
jni
cvs2svn
cruisecontrol.net
jquery-form-validator
iup
rworldmap
bootstrap-typeahead
fabric
net-snmp
skmaps
osmdroid
roundcube
consumer
outsystems
receipt
threshold
nodeclipse
initializer
concrete5-5.7
fax
pdftk
rich-text-editor
asmx
email-parsing
tableau-server
proof
gist
multi-agent
persistent
spring-data-hadoop
heroku-postgres
pycurl
project-template
libtiff.net
android-navigationview
slam-algorithm
asteriskami
shipitjs
console-redirect
anti-cheat
group-concat
magento-1.4
altbeacon
multinomial
insert-into
lmfit
paypal-nvp
wif
lines-of-code
adobe-indesign
virus
client-side-validation
inputaccessoryview
left-recursion
ultrawingrid
smartystreets
late-static-binding
map-force
json-patch
logentries
installshield-2011
sttwitter
nuspec
qss
magickwand
process-monitor
autostart
rose-db-object
cross-domain-policy
ajax.beginform
nemerle
windows-live-id
smooth
quick-search
scala-2.8
evb
associativity

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