Q:

A subset of a list with elements available in another list

I'm new in python.
I want to get a subset of a list with elements available in another list.
If I want to do it in R, I would do:
aa=c(1,1,1,1,2,2,2,3,3,4)
bb=c(1,4)
aa[aa %in% bb]
# 1 1 1 1 4

Would you please translate this code from R to python?
Many thanks

A:

Use a list comprehension, treating b as a set for efficient membership testing:
a = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
b = {1, 4}
result = [elem for elem in a if elem in b]

Demo:
>>> a = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
>>> b = [1, 4]
>>> b_set = set(b)
>>> [elem for elem in a if elem in b_set]
[1, 1, 1, 1, 4]

