Skip to content
Advertisement

Python: Proper use of any() to check if one value of one array exists in another array?

In Python, I am trying to create an if statement that proceeds if one variable of one array exists somewhere in another list or array. Here is my basic code, which is supposed to check if any of the values within ids exist in follow_num:

ids = [123,321,111,333]
follow_num = [111, 222]

if any(ids == follow_num):
    print(ids)

Despite my best attempts, and many versions of the above, I cannot get this to work. Could someone please elaborate where I am going wrong here?

Advertisement

Answer

You must loop through each value in ids and check if any of those values exist in follow_num. Use any with a generator comprehension:

if any(i in follow_num for i in ids):
    print(ids)

Output:

[123,321,111,333]

Edit:

If you want to print any matches any() doesn’t work, you must use a for loop since any() computes for the entire list. Example:

for i in ids:
    if i in follow_num: print(i)

Note that you can speed up both of these operations by converting follow_num beforehand to a set() by doing follow_num = set(follow_num). This is faster because set has an O(1) in operation, compared to lists which compute in in O(N).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement