Reputation: 109964
I'm starting to learn a bit more about Python. One function I often want but don't know how to program/do in Python is the x %in% y
operator in R. It works like so:
1:3 %in% 2:4
##[1] FALSE TRUE TRUE
The first element in x
(1) has no match in y
so FALSE
where as the last two elements of x
(2 & 3) do have a match in y
so they get TRUE
.
Not that I expected this to work as it wouldn't have worked in R either but using ==
in Python I get:
[1, 2, 3] == [2, 3, 4]
# False
How could I get the same type of operator in Python? I'm not tied to base Python if such an operator already exists elsewhere.
Upvotes: 3
Views: 1934
Reputation: 394
It's actually very simple.
if/for element in list-like object.
Specifically, when doing so for a list it will compare every element in that list. When using a dict as the list-like object (iterable), it will use the dict keys as the object to iterate through.
Cheers
Edit: For your case you should make use of "List Comprehensions".
[True for element in list1 if element in list2]
Upvotes: 3
Reputation: 545865
%in%
is simply in
in Python. But, like most other things in Python outside numpy, it’s not vectorised:
In [1]: 1 in [1, 2, 3]
Out[1]: True
In [2]: [1, 2] in [1, 2, 3]
Out[2]: False
Upvotes: 2