Python program to find out numbers in a list divisible by two numbers

Introduction :

In this python programming tutorial, we will learn how to find all numbers that are divisible by two specific numbers. For example, let’s take a look at the list [1,2,3,4,5]. In this list, numbers that are divisible by 2 and 1 are [2,4]. Our program will do the same thing. The user will enter the values of the list and also the two numbers (let’s say m and n).
This is a beginner friendly program and it will give you the basic understanding of loops, conditions, list and how to take user input in python. Let’s take a look at the program first :

Python program :

#1
list_size = int(input("How many numbers are in the list : "))

#2
number_list = []
final_list = []

#3
for i in range(0,list_size):
    number_list.append(int(input("Enter list item {} : ".format(i))))

#4
m = int(input("Enter the first divider : "))
n = int(input("Enter the second divider : "))

#5
for i in range(0,list_size):
    if number_list[i] % m == 0 and number_list[i] % n == 0 :
        final_list.append(number_list[i])

#6
print("Numbers that are divisible by {} and {} is : ".format(m,n),final_list)

Explanation :

The commented numbers in the above program denote the step number below :

1. Ask the user how many numbers the list will hold. Read the input and store it in list_size variable.
2. Create two empty lists. number_list will hold all the numbers and result_list will hold the final list of numbers.
3. Run one for loop. Ask the user to enter list item. Read it and store it in number_list list.
4. Ask the user to enter the value for m and n. Read it and store it in variable m and n.
5. Run one more for loop. Check for each number if it is divisible by m and n or not. If yes, add that value to the final_list. So, final_list will store all the result numbers.
6. Finally, print out all the numbers that are in the final_list.

Sample Output :

How many numbers are in the list : 5
Enter list item 0 : 1
Enter list item 1 : 2
Enter list item 2 : 3
Enter list item 3 : 4
Enter list item 4 : 5
Enter the first divider : 1
Enter the second divider : 2
Numbers that are divisible by 1 and 2 is :  [2, 4]

How many numbers are in the list : 7
Enter list item 0 : 2
Enter list item 1 : 3
Enter list item 2 : 5
Enter list item 3 : 6
Enter list item 4 : 8
Enter list item 5 : 12
Enter list item 6 : 44
Enter the first divider : 4
Enter the second divider : 2
Numbers that are divisible by 4 and 2 is :  [8, 12, 44]

python find list number divisible by two other numbers

Conclusion :

We have learnt how to find all numbers in a list divisible by m or n in python. Go through the above example and drop a comment below if you have any queries. Happy Coding 🙂

You might also like :

Leave a Reply