Search code examples
pythonpython-3.xlistlist-comprehensionor-operator

Using an 'or' operator in a basic python list comprehension


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

how-to-convert-this-my-code-into-a-list-comprehension

python-list-comprehension-with-multiple-ifs


Solution

  • Don't use another if!

    numbers = [x for x in range(99) if (x % 5 == 0) or (x % 7 == 0)]
    print(numbers)
    

    Because if is a statement and those are expressions, and then do or and use if shorthand to check.