Checking a List for Values from Another List

Your mother is at the local farmers market. She calls you from the fruit stand there and asks whether you want her to pick anything up for you. You tell her yes, but only if they have any of your favorites. She says okay, and hangs up.
If this were a Python program, we could think about this as follows: Are any of the fruits in my list of favorites among those available for sale? We could structure it like this:
# Fruits that are available
fruits4sale = ['apple', 'banana', 'cherry']
# My favorite fruits
my_favorites = ['apple', 'date']
We want a way to test (True
or False
) whether any item in my_favorites
is in fruits4sale
.
if any(t in fruits4sale for t in my_favorites):
print("The first list contains at least one of my favorites!")
else:
print("The first list does NOT contain any of my favorites. :-(")
The resulting output is:
The first list contains at least one of my favorites!
Hooray, it works!
Why does this work?
The any()
function returns True
if at least one of the values in a list is True
.
In the code above, the list we are passing to the any()
function is the result
of a list comprehension:
t in fruits4sale for t in my_favorites
This tells python to construct a list of Booleans based on the test t in fruits
—that is, True
if t
is member of the list fruits
and False
otherwise. But what is t
? It takes on each
value found in the my_favorites
list in turn. In other words, we evaluating each of the favorite
fruits one at a time to see if it’s in the list of available fruits. The result is a list of True
or False
values representing each favorite. If any of those is True
then the overall result
is True
.
Note: List comprehensions are usually found enclosed in brackets, but in the code above the function parentheses serve to “contain” the list.
So let’s try again with a different list of fruits.
fruits2 = ['banana', 'cherry', 'elderberry']
if any(t in fruits2 for t in my_favorites):
print("The second list contains at least one of my favorites!")
else:
print("The second list does NOT contain any of my favorites. :-(")
The second list does NOT contain any of my favorites. :-(
Now you know how to check to see if a list contains any values from another list.