marue
marue

Reputation: 5726

Python Boolean: any value of a list in another list or dictionary

I just recently found myself writing this line of code, which i did not like too much:

if ('upload' in request.POST) or ('delete' in request.POST):

I allready thought about list comprehension, which would look like this:

if [value for value in ['upload','delete'] if value in request.POST]:

Which is not exactly better. My very simple question is: can this be simplified? Or is this just trying to be too smart?

Upvotes: 0

Views: 228

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

Simplification uses any().

if any(value for value in ['upload','delete'] if value in request.POST):

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839254

You could write it more concisely by using set intersection:

if {'upload', 'delete'} & set(request.POST):

Or more explicitly:

if {'upload', 'delete'}.intersection(request.POST):

Upvotes: 6

Related Questions