-1

Trying to do something like the following:

a = [{'fruit':'apple', 'color':'red'}, {'fruit':'pear', 'color':'blue'}, {'fruit':'pineapple', 
'color':'green'}]

for object in a:
    if 'pineapple' or 'pear' in object['fruit']:
         if 'pear' in object['fruit']:
             a.remove(object)

I tried something like this but it deletes every pear every time. I need it to only remove the object with 'pear' from the list, if an apple or pineapple object is present. If a pear object is by itself, I need it to not be removed. I'm guessing it is iterating through the same object but I'm not sure how to write it out.

Thanks

Meme-ento
  • 3
  • 2

1 Answers1

0

First check the pineapple condition:

if any('pineapple' in o['fruit'] for o in a):

and then rebuild a according to the pear criteria (don't try to remove items from a while iterating over it, just build a new list):

    a = [o for o in a if 'pear' not in o['fruit']]

All together:

>>> a = [{'fruit':'apple', 'color':'red'}, {'fruit':'pear', 'color':'blue'}, {'fruit':'pineapple',
... 'color':'green'}]
>>>
>>> if any('pineapple' in o['fruit'] for o in a):
...     a = [o for o in a if 'pear' not in o['fruit']]
...
>>> a
[{'fruit': 'apple', 'color': 'red'}, {'fruit': 'pineapple', 'color': 'green'}]
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 1
    can i have two clauses in the if any? like if any('pineapple' or 'apple' in o['fruit'] – Meme-ento May 24 '23 at 02:26
  • @Meme-ento yes, you can do like this: `if any('apple' in item['fruit'] or 'pineapple' in item['fruit'] for item in a):`. Note that `if any('apple' or 'pineapple' in item['fruit'] for item in a):` does not work as intended. You can also do: `if any('apple' in item['fruit'] for item in a):`; this works because the `'apple' in item['fruit']` checks if there are any occurrences of the string "apple" in the item, and there is an occurrence of "apple" in "pineapple"; this removes the redundancy of the code in this specific case, but remember that sometimes its better to be explicit than implicit. – Davi A. Sampaio May 24 '23 at 02:55