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

How to animate font size without text reordering, when `text_size=self.size`
How to import the last row from array of excel files to another excel using openpyxl
how to terminate a thread which calls the webbrowser in python
Can I load HTML on Ghost.py
Combining two lists of names and sorting them to make one sorted list of names
Python equivalent of bash sort lexicographical and numerical
Why isn't my frames background showing?
Trying to do a natural join using python standard library
How to combine several querysets by key in common?
How I can speed up row column access to pandas dataframe?
Create list with combinations of 3 elements of other list with repetitions
PyQt5 does not change gifs
Pydub - combine split_on_silence with minimum length / file size
how to choose python version accordingly in pycharm?
Unable to import Flask to Kivy iOS
Unique list without spliting entries based on spaces in python

Categories

HOME
swift
google-apps-script
cakephp-3.x
crystal-reports
admin-on-rest
google-cloud-bigtable
npm
angular-cli
ncurses
facebook-graph-api
actionscript
laravel-5.2
concourse
zend-framework2
apollo
recyclerview
azureservicebus
algorithmic-trading
websphere-liberty
xcode8.3
onenote-api
gimp
octopus-deploy
cakephp-2.9
gatsby
xlsx
scaling
android-toolbar
internet-explorer-8
sonarqube-msbuild-runner
countif
ui5
hash-collision
ggmap
system.data.sqlite
mayavi
cortex-m3
websauna
lmdb
twitter-bootstrap-2
clockwork
expand
modelandview
mapguide
reactivemongo
phpspreadsheet
von-neumann
declare
duktape
alchemy.js
restful-url
tripwire
microdata
amd
openweathermap
azure-availability-set
range-v3
proof
defold
pluck
crystal-reports-8.5
unity3d-editor
cleditor
picasa
slam-algorithm
mix
uiprogressview
android-recyclerview
test-class
android-viewholder
rad
python-winshell
programming-paradigms
manjaro
start-job
django-1.6
moai
cloudpebble
jquery-autocomplete
grunt-contrib-concat
ember-components
node-imagemagick
log4cplus
dto
proxies
spdy
lov
jquery-tabs
sim900
magicalrecord-2.2
javascriptmvc
shiva3d
soa-suite
client-library
dropdownlistfor
cadisplaylink
wcf-web-api
selectonemenu
msbuildextensionpack
testunit
exitstatus
sitemappath
aio
callgrind
kpi
data-entry
web-analytics-tools
interface-design
document-library





Mobile Apps Dev
Database Users
javascript
java
csharp
php
android


MS Developer
developer works
python
ios
c
html
jquery


RDBMS discuss