0

I faced with a usage of any() like this:

return any(node.state == state for node in self.frontier)

When I checked, any() returns True if any element of an iterable is True.So i think that if any() checks any element of an iterable, why do we use for loop? it already checks every element in it..

Another thing I didn't understand with this syntax is that what does it do in for loop? it is at the end of the line, and there is nothing after it..

Wokers
  • 107
  • 3
  • 13

2 Answers2

2

First of all, the built-in function any(iterable) does roughly the same as:

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

Regarding your particular case, you actually have an iterable of nodes, so you can't use any(self.frontier) directly. What you really need is a way to convert your original iterable into another one where each element is compared with the given state. And Python provides a compact syntax for such kinds of transformations called generator expressions. Thus, node.state == state for node in self.frontier is just an easy way to convert your initial iterable of nodes (i.e. self.frontier) into an iterable of booleans.

Gevorg Davoian
  • 484
  • 5
  • 13
1

In the following example you might see the difference:

from collections import namedtuple
Node = namedtuple('Node', ['state'])

state = 2
frontier = [Node(1), Node(1)]

print("Any frontier:", any(frontier))
print("Any state:", any(node.state == state for node in frontier))

The output is:

Any frontier: True
Any state: False

From the any documentation: Return True if any element of the iterable is true.

In the first case the iterable is the frontier and element in the iterable is the element in the frontier array.

In the second case the iterable is the list of comparisons between node.state and state and element is the result of this comparison.

Benjamin
  • 3,217
  • 2
  • 27
  • 42