-5
def divisible_by(numbers, divisor):
    return [x for x in numbers if x % divisor == 0]

i know it returns the divisible numbers from the array of numbers, but can someone explain how it gets there?

I am learning python as my first language, but i have not got to arrays yet.

i am mostly confused by this part "x for x in numbers if x"

Thanks

Prune
  • 72,213
  • 14
  • 48
  • 72
Jperkins98
  • 37
  • 10
  • 5
    https://www.pythonforbeginners.com/basics/list-comprehensions-in-python – SLaks Mar 12 '19 at 22:26
  • 3
    If you search on the phrase "Python list comprehension", you’ll find resources that can explain it much better than we can in an answer here. – Prune Mar 12 '19 at 22:27
  • Welcome to Stack Overflow. All the downvotes are related to you not understanding the reason for Stack Overflow. Please read this -- How to create a Minimal, Complete, and Verifiable example -- https://stackoverflow.com/help/mcve and repost your question or move it to https://codereview.stackexchange.com. – Life is complex Mar 12 '19 at 22:33
  • 1
    Possible duplicate of [What does “list comprehension” mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – pault Mar 12 '19 at 22:34

1 Answers1

1

This is what is called "list comprehension". In one line, it creates a new list of all the numbers in "numbers" that are divisible by divisor. That's what the modulo (%) is checking. It checks that the remainder of the division is equal to 0.

The list comprehension is equivalent to saying:

divisible_numbers = []
for x in numbers:
    if x % divisor == 0:
        divisible_numbers.append(x)
return divisible_numbers
minterm
  • 245
  • 3
  • 13