How to use any generators to check a string is part of a list of other strings?

Viewed 212

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?'

1 Answers

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.

Related