3

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.

4
  • Would that be [x in range(2,5) for x in range(1,4)] ? Commented Jul 26, 2016 at 20:41
  • 5
    stackoverflow.com/questions/25206376/… Commented Jul 26, 2016 at 20:41
  • 1
    How is this a duplicate? The other question asks for a panda-specific solution and the answer has nothing to do with general concept of 'in'. Commented Jul 26, 2016 at 20:54
  • 1
    Could do for i in x: [].append(i in y) or [i in y for i in x] Commented Jul 26, 2016 at 21:10

2 Answers 2

3

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] 
Sign up to request clarification or add additional context in comments.

3 Comments

I’m not sure I understand your answer — if element in list-like object and for element in list-like object are two fundamentally different operations in Python. The second one performs iteration, not a membership test. The first one performs the membership test (see my answer) but the if isn’t part of the syntax.
I know. I just wanted to demonstrate other uses of the 'in' keyword.
Good use of if. Plus one.
2

%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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.