1

I am reading about any() in python and I am not sure how to use it.

My case is as follows: Given two lists of server names, list A and list B, I need to check if any of the names from A matches to B.

I found these two questions that is similar to what I am trying to do:

But I am not understanding the code of any() very well. Is the below what I am supposed to do with the generator?

any(X in listA for Y in listB)

means 'If any item X in listA is truthty against each item Y in listB return true?'

martineau
  • 119,623
  • 25
  • 170
  • 301
D.Zou
  • 761
  • 8
  • 25

1 Answers1

3

I think that what you really want is to check whether the intersection of set A and set B is non empty.

If you want to follow the any route, you want the following expression any(x in listA for x in listB).

The function any is basically a function which chains or.

any([True,False,True]) // === True or False or True (which is True)

The expression x in listA is either True if x (which is an element of listB is also an element of listA). [x in listA for x in listB] creates a list of booleans (and (x in listA for x in listB) creates a generator with the same elements), which tells us which elements of listB are in listA. If at least one of those booleans is True that means that some server names in listA are also in listB.

永劫回帰
  • 652
  • 10
  • 21
  • 1
    this is not a generator :) need double parenthesis – Bing Wang Jan 26 '21 at 22:26
  • 1
    They are optional, `x in listA for x in listB` is not a standalone valid Python expression but `(x in listA for x in listB)` is a generator. However, `any(x in listA for x in listB)` works fine, even without the double parenthesis. – 永劫回帰 Jan 26 '21 at 22:35
  • 1
    @BingWang: no. You do not need double parens to make a generator, or even single parens if the generator expression is constructed as a argument, as is the case for `any()`. Try this to demonstrate: `def f(g): print(g)` and then call with `f(a in B for a in A)` – mhawke Jan 26 '21 at 22:40
  • I have removed the optional double parentheses – 永劫回帰 Jan 26 '21 at 22:42
  • 1
    It's important to understand that the implementation of `any(iterable)` does not evaluate every item in the iterable before returning, unless all items in the iterable are "false". `any()` will return `True` as soon as it sees the first "true" item if there is one. `any()` does not perform an OR operation on all of the items, it iterates over the iterable and returns as soon as possible. See the documentation for [`any()`](https://docs.python.org/3/library/functions.html?#any). – mhawke Jan 26 '21 at 23:06