0

I have a section of code looks like this

fruits = ["apple", "banana", "orange", "apple"]

found_apple = False

for f in fruits:
    if f == "apple":
        found_apple = True
if not found_apple:
    raise ValueError('Apple is not found')

I can feel a bad smell so I simplify it to like:

fruits = ["apple", "banana", "orange", "apple"]

if not any([f for f in fruits if f == "apple"]):
    raise ValueError('Apple is not found')

but it increase the space complexity because it create a list. How can you simplify it and make it more redable without losing the time complexity and space complexity?

Aaron Wei
  • 85
  • 1
  • 5

0 Answers0