Reputation: 29
I'm currenty learning list comprehension in Python and I want to write a function that takes two lists, a
and b
, and returns all elements of a
that are divisible by all elements of b
.
The equivalent of this (not using list comprehension) would be:
a = [10, 5]
b = [5, 2]
c = []
d = True
for i in a:
for j in b:
if i % j != 0:
d = False
if d:
c.append(i)
return c
How can I do this with list comprehension?
I currently have [x for x in a for y in b if x % y == 0]
but that only requires x to match one of the items in b, not all of them.
Upvotes: 0
Views: 54
Reputation: 1465
Try this one:
a = [10, 5]
b = [5, 2]
res = [x for x in a if all(x % y == 0 for y in b)]
for completion on @superb rain 's comment. Here is also an example for any(...):
res = [x for x in a if not any(x % y != 0 for y in b)]
Upvotes: 1