First off, your code needs to be corrected to something like this:
def f(x):
for k in K:
yield [i for i in x if i <= 1 + k or i >= 4 + k]
With this correction, list(f(range(0, 10)))
produces [[0, 1, 2, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 8, 9]]
.
The next step is to filter for elements that are an intersection both sets. This can be done in a number of ways, as shown in the question Find intersection of two lists?.
Here is my preferred method of doing it, based on this answer:
def intersect(lists):
count = len(lists)
if count == 0:
return []
elif count == 1:
return lists
elif count == 2:
es1 = set(lists[1])
return [x for x in lists[0] if x in es1]
else:
return intersect((lists[0], intersect(lists[1:])))
Now, using the corrected version of the function you wrote in your question with the intersect
function, you get the intended result, as shown below:
result = list(f(range(0, 10)))
result
# [[0, 1, 2, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 8, 9]]
intersect(result)
# [0, 1, 2, 5, 8, 9]
WARNING!!
Potential Pitfall:
Python will allow you to give a variable the name of a standard function. Doing this, however, will shadow the function whose name you have taken, making the function hidden and could result in unexpected behaviour. It is therefore recommended that you change the name of your list
variable to something else. You can try, for example, l1
or list1
.