Question: How can I use OR in a python list comprehension?
I am looking to output any number between 0-99 that is either divisible by 5 or 7 with no remainder. I have the following code:
numbers = [x for x in range(99) if x % 5 == 0 if x % 7 == 0]
but this returns: 0, 35, 70 which are the numbers divisible by both 5 and 7. I also tried:
numbers = [x % 5 == 0 or x % 7 == 0 for x in range(99)]
but this returns True or False for each number, where I am looking to get the numbers themselves. Using this:
numbers = [x for x in range(99) if x % 5 == 0 or if x % 7 == 0]
throws a syntax error.
I have looked over the following pages but was not able to understand how to apply the solutions if they were presented. They each seemed to offer nuances to my desired solution, but were not what I was looking for.
datacamp.com/community/tutorials/python-list-comprehension
programiz.com/python-programming/list-comprehension
use-of-or-operator-in-python-lambda-function
not-comprehending-list-comprehension-in-python
is-there-a-binary-or-operator-in-python-that-works-on-arrays
Don't use another
if
!Because
if
is a statement and those are expressions, and then door
and useif
shorthand to check.