How can I check if numbers in a range are divisible by one of two numbers?


#1

Question

How can I check if numbers in a range are divisible by one of two numbers?

Answer

n “Comprehending Comprehensions”, we’re asked to create a list using list comprehension that contains numbers between 1 and 15 (inclusive) that are divisible by 3 or 5.
The basic syntax, without giving away the answer, looks like this:
my_list = [var for var in range(start, stop) if condition_1 or condition_2
The conditions we’re checking are for the variable to be evenly divisible by 3 or 5, which we can do using the modulo % operator.
To check if something is divisible by 2, we’d write if x % 2 == 0:.


FAQ: Learn Python - Advanced Topics in Python - Comprehending Comprehensions