Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable matches any item in list using the any() function?

Edit: This is what I am trying to do: I am asking the user to enter a month. then the code will lookup if the month is correct by checking every item in months_list. If not found I want him/her to enter the month again..

Here's the code:

months_list=["January", "February", "March", "April", "May", "June", "July"]
answer=raw_input("Month? \n")
while any(item.lower() != answer.lower() for item in months_list):
    print("Sorry, didn't recognize your answer, try again")
    answer=raw_input("Type in Month\n")

However this keeps looping regardless if the month is found in the list or not.. I hope this is a good clarifaction.. thank you all in advance

like image 894
Aous1000 Avatar asked Apr 09 '14 19:04

Aous1000


People also ask

How do you check if any value is in a list Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.

How do you check a condition for all elements in a list?

Method #1 : Using all() We can use all() , to perform this particular task. In this, we feed the condition and the validation with all the elements is checked by all() internally.

How do you check if the value is in the list?

Besides the Find and Replace function, you can use a formula to check if a value is in a list. Select a blank cell, here is C2, and type this formula =IF(ISNUMBER(MATCH(B2,A:A,0)),1,0) into it, and press Enter key to get the result, and if it displays 1, indicates the value is in the list, and if 0, that is not exist.


Video Answer


3 Answers

The problem is that any() returns True if any one of the elements in the iterable is True, so your code keeps looping as long as the answer isn't equal to all the strings in months_list—which is probably the opposite of what you want to happen. Here's a way to use it that stops or breaks-out of the loop if the answer matches any of the strings:

months_list = ["January", "February", "March", "April", "May", "June", "July"]

while True:
    answer = raw_input("Month? ")
    if any(item.lower() == answer.lower() for item in months_list): 
        break
    print("Sorry, didn't recognize your answer, try again")

As others have pointed out, while it would simpler to use Python's in operator, that way still results in a linear search, O(n), being performed…so an even better (faster) approach would be to use a set of lower-cased month_names, which would utilize a hash table based look-up, O(1), instead of a linear search:

months = set(month.lower() for month in ("January", "February", "March", "April",
                                         "May", "June", "July"))
while True:
    answer = raw_input("Month? ")
    if answer.lower() in months: 
        break
    print("Sorry, didn't recognize your answer, try again")

Further refinement

Depending on the nature of strings involved and why you're comparing them, it might be better to use the string casefold() method instead of lower() to do caseless string comparisons.

like image 171
martineau Avatar answered Oct 18 '22 00:10

martineau


any(a) means "is any item in a truthy"? And the result is True because every item in a is truthy. (Any non-zero-length string is truthy, and every item in a is a non-zero-length string.)

And then you are comparing that result, True, to, say, "A". True is not equal to "A" so the result of that comparison is, of course, False.

What you probably want to do is something like:

"A" in a   # True

If you must use any() for some reason, try:

any(item == "A" for item in a)

This approach has the advantage of being able to do imprecise comparisons easily (in will only do exact comparisons). For example:

any(item.lower() == "a" for item in a)   # case-insensitive
any("a" in item.lower() for item in a)   # substring match
any(item.lower().startswith("a") for item in a)
like image 20
kindall Avatar answered Oct 18 '22 00:10

kindall


To check membership, use in:

>>> a = ['a','b','c','d']
>>> 'a' in a
True
>>> 'z' in a
False
like image 12
bgporter Avatar answered Oct 17 '22 23:10

bgporter