Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to print elements which are multiples of elements given in a list
When we need to find elements that are multiples of all elements in a given list, we can use list comprehension with the all() function. This approach efficiently filters elements that satisfy the multiple condition for every element in the divisor list.
Example
Below is a demonstration of finding multiples using list comprehension ?
numbers = [45, 67, 89, 90, 10, 98, 10, 12, 23]
print("The list is:")
print(numbers)
divisors = [6, 4]
print("The division list is:")
print(divisors)
multiples = [element for element in numbers if all(element % j == 0 for j in divisors)]
print("The result is:")
print(multiples)
The list is: [45, 67, 89, 90, 10, 98, 10, 12, 23] The division list is: [6, 4] The result is: [12]
How It Works
The list comprehension uses the all() function to check if each element is divisible by every number in the divisors list:
List comprehension ? Iterates through each element in the main list
all() function ? Returns
Trueonly if all conditions are metModulo operation ?
element % j == 0checks if element is divisible by jGenerator expression ? Creates conditions for each divisor efficiently
Alternative Approach Using Functions
Here's a function-based approach for better reusability ?
def find_multiples(numbers, divisors):
"""Find elements that are multiples of all divisors"""
return [num for num in numbers if all(num % div == 0 for div in divisors)]
# Example usage
data = [24, 36, 48, 15, 30, 60, 72]
divisor_list = [3, 6]
result = find_multiples(data, divisor_list)
print(f"Numbers: {data}")
print(f"Divisors: {divisor_list}")
print(f"Multiples of all divisors: {result}")
Numbers: [24, 36, 48, 15, 30, 60, 72] Divisors: [3, 6] Multiples of all divisors: [24, 36, 48, 30, 60, 72]
Conclusion
Use list comprehension with all() to efficiently find elements that are multiples of all given divisors. This approach is concise and leverages Python's built-in functions for optimal performance.
