The ‘any’ keyword in Python


I came across the any keyword in Python a couple days ago when I was trying to solve the problem in https://helloacm.com/a-sleuth/

At that time I did not fully understand this keyword and the solution using any luckily got accepted even I did not need the keyword.

The any is actually a function, built-in and defined as follows:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

As you can see, it takes a parameter which is iterable. Previously, I thought to check if an item is in a list is to use the following:

any(x in y for y in z)

Well, this happens to be right in some cases. The correct solution to check if an item is in a list is simpler.

x in z

What is the difference? The first any is to check x in every sub iterable. For example,

z = ['8', '9', '10', '2', '3']
['1' in y for y in z]
#produces
[False, False, True, False, False]

That is why in that problem, both expressions got accepted but actually using x in z is correct. Both expressions got accepted because the maximum character length is one so they both ‘effectively’ true.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
288 words
Last Post: The github experience
Next Post: Codeforces: B. Permutation

The Permanent URL is: The ‘any’ keyword in Python

Leave a Reply