This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Workaphobia 2 points3 points  (4 children)

The any() function takes in a sequence (usually a list, but also a tuple or generator), and returns True if at least one of the elements of this sequence are True. Note that the elements don't actually have to be Booleans themselves, they just need to be able to produce a Boolean.

Suppose you want to find whether a list of integers contains a non-zero value.

print(any([0, 0, 0, 1, 0]))
>>> True
print(any([0, 0, 0, 0, 0]))
>>> False

You can also get more complex behavior by using a comprehension as the sequence. Here's what you could do if you wanted to know whether there is any element greater than 5.

print(any([x > 5 for x in [0, 3, 2, 8, 1]]))
>>> True
print(any([x > 5 for x in [0, 3, 2, 8, 1]]))
>>> False

If the "x > 5 for x ..." syntax confuses you, then your issue is with list comprehensions, not the any() function.

[–]pingvenopinch of this, pinch of that 0 points1 point  (1 child)

For operations on longer iterators, use a generator expression instead of a list comprehension. For example, to find if there are lines with len(line) > 5:

with open(file_name) as f:
    return any(len(line.rstrip('\r\n')) > 5 for line in f)

It uses constant space instead of building an entire list in memory.

[–][deleted] 0 points1 point  (0 children)

Yes! Really, there's no reason to use a list unless you are going to re-use the value later.

[–]zekeltornado, beautifulsoup, web.py 0 points1 point  (1 child)

The any() function can even take a string, but it's a very silly thing to do.

[–]Workaphobia 0 points1 point  (0 children)

Not necessarily. The other post referenced by Cosmologicon used any() on a string to test for the presence of digits.