Finding Numbers Divisible by Another Number

To check if a number is completely divisible by another number, we use Python modulo operator, which is a part of the arithmetic operators. If the number is completely divisible by another number, it should return 0 as the remainder. If the remainder is other than 0, that means that the number is not completely divisible.

Now, let us see a few different ways to find all the numbers in a given list that are divisible by another number.

For Loop

In this example, we will use Python for loop to iterate over each element in the list. Then the extracted element id is checked for divisibility with the divisor by using the modulo operator. If it returns 0, then that number is added to another list that contains all the elements that were divisible by the divisor.

Python
def find_divisibles(myList, num):
    
    # list to store divisible numbers
    divisibles = []
    
    # for loop for iteration
    for i in myList:
        # checking if the number is divisible
        if i % num == 0:
            # adding number to new list
            divisibles.append(i)
            
    return divisibles

myList = [8, 14, 21, 36, 43, 57, 63, 71, 83, 93]
num = 3
print(find_divisibles(myList, num))

Output:

[21, 36, 57, 63, 93]

List Comprehension

List comprehensions provide a concise way to generate lists. We can use this feature to create a list of numbers that are divisible by another number in a single line of code.

Python
def find_divisibles(myList, num):
    # list comprehension to check if the number is divisible
    return [i for i in myList if i % num == 0]

myList = [8, 14, 21, 36, 43, 57, 63, 71, 83, 93]
num = 3
print(find_divisibles(myList, num))

Output:

[21, 36, 57, 63, 93]

Python Program to Find Numbers Divisible by Another Number

We are given a list of numbers and a number. We have to find all the numbers in the list that are divisible by the given single number.

Examples:

Input: list=[8, 14, 21, 36, 43], num=3
Output: 21, 36, 57

Input: list=[2, 17, 25, 31, 48, 55], num=5
Output: 25, 55

In this article, we will discuss the different ways to find numbers divisible by another number in Python.

Similar Reads

Finding Numbers Divisible by Another Number

To check if a number is completely divisible by another number, we use Python modulo operator, which is a part of the arithmetic operators. If the number is completely divisible by another number, it should return 0 as the remainder. If the remainder is other than 0, that means that the number is not completely divisible....

The filter() and Lambda Functions

The filter() function in Python can be used to construct an iterable from elements of another iterable that satisfy a specific condition. When combined with a lambda expression, it provides a clean way to filter out numbers based on divisibility. The list() function is used to convert the result back into a list....