0

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?

Coolio2654
  • 1,589
  • 3
  • 21
  • 46

3 Answers3

2

Alternatively you can compare two sets:

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

matches = list(set(ids) & set(follow_num))

print(matches)
# [111]

print(bool(matches))
# True
Darius
  • 10,762
  • 2
  • 29
  • 50
  • I would wonder what the speed of this method is, hmm, but it looks interesting. – Coolio2654 Feb 07 '19 at 23:57
  • @Coolio2654 It scales much better than the answer by Primusa in its current form. However if `ids` was converted to a `set` first in the answer by Primusa it would scale well too. Darius should keep in mind the conversion of `matches` to `list(...)` is useless – jamylak Feb 08 '19 at 05:21
  • Also, `any(matches)` is wrong, because `any([0])` is `False` and `0` could be a valid `id`. You should simply just check `if matches` or `print bool(matches)` – jamylak Feb 08 '19 at 05:23
1

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).

Primusa
  • 13,136
  • 3
  • 33
  • 53
  • Quick question, is there an obvious way to make the if statement within the for loop a list comprehension? – Coolio2654 Feb 07 '19 at 23:47
  • You can do something like `[print(i) for i in ids if i in follow_num]`, but that defeats the purpose of the list comprehension - you're using it to print values not to build a list. – Primusa Feb 07 '19 at 23:48
  • 1
    A good resource for conditionals in list comprehensions would be here: https://stackoverflow.com/questions/4260280/if-else-in-pythons-list-comprehension – Primusa Feb 07 '19 at 23:49
  • Thanks for all the help and the reference. – Coolio2654 Feb 07 '19 at 23:58
  • @Coolio2654 happy to help :) – Primusa Feb 07 '19 at 23:59
0
>>> ids = [123,321,111,333]
>>> follow_num = [111, 222]
>>> if set(ids).intersection(follow_num): 
...   print(ids)
... 
[123, 321, 111, 333]
jamylak
  • 128,818
  • 30
  • 231
  • 230