pythonlist

Python list to feed a selection Or clause


If I have a python list that I want to generate a selection clause from. How do I do this elegantly?

Example list:

fruit = ['apple', 'blackberry', 'peach', 'kiwi']

and I want a resultant SQL clause string variable set like:

item_field = 'apple' Or item_field = 'blackberry' Or item_field = 'peach' Or item_field = 'kiwi'

I have tried a few things ("item_field = {}".format(' Or '.join(fruit)) -- somewhat close) and Googled, but just not getting what I am looking for.


Solution

  • If you are looking for a string, then this is an easy solution:

    " Or ".join(f"item_field = '{fruit}'" for fruit in fruits)