5 Best Ways to Print All Numbers in a Range Divisible by a Given Number in Python

Rate this post

πŸ’‘ Problem Formulation: You are given two integers forming a range and another integer ‘n’. The task is to write a Python program to print all numbers within that range that are divisible by ‘n’. For example, given the range [1, 10] and the number 2, the desired output is 2, 4, 6, 8, 10.

Method 1: Using a Basic for-loop

This method involves iterating through the entire range using a for-loop and checking if each number is divisible by the given divisor with the modulo operator. It’s the most straightforward approach and is ideal for beginners to understand the concept of loop iteration and conditional statements in Python.

Here’s an example:

for i in range(1, 11):
    if i % 2 == 0:
        print(i)

Output:

2
4
6
8
10

This code snippet creates a loop that iterates from 1 to 10 inclusive. It checks if the current number ‘i’ is divisible by 2 using the modulo operator. If the remainder is zero, it’s divisible, and the number is printed.

Method 2: Using List Comprehension

List comprehension in Python can be used to create a more compact method for finding divisible numbers. This method utilizes a single line of code to iterate through the range and select numbers which meet the criteria, resulting in a cleaner and perhaps more “Pythonic” solution.

Here’s an example:

print([i for i in range(1, 11) if i % 2 == 0])

Output:

[2, 4, 6, 8, 10]

Here, we use list comprehension to iterate through numbers 1 through 10, and we print a list that consists of only those numbers that are divisible by 2.

Method 3: Using the filter() Function

The filter() function in Python can be employed to filter out the numbers that are not divisible by the given number. It neatly abstracts away the iteration and makes the code easy to read and understand for those familiar with functional programming in Python.

Here’s an example:

filtered_numbers = filter(lambda x: x % 2 == 0, range(1, 11))
print(list(filtered_numbers))

Output:

[2, 4, 6, 8, 10]

This code uses the filter() function with a lambda function that returns true if the number is divisible by 2. The filter() function applies this lambda to each item in the range, and list() converts the result into a list.

Method 4: Using NumPy

For those working within the data science domain or dealing with large datasets, NumPy provides a highly optimized array operation suite that can handle such operations in a vectorized manner. While this is overkill for smaller ranges, it’s perfect for large scale applications.

Here’s an example:

import numpy as np

nums = np.arange(1, 11)
print(nums[nums % 2 == 0])

Output:

[ 2  4  6  8 10]

This code initializes a NumPy array with the specified range and then prints elements where the condition (division by 2 equals zero) is true. It’s concise and faster on large datasets.

Bonus One-Liner Method 5: Using a Generator Expression

A generator expression is similar to list comprehension but creates an iterable generator instead of a list. It is memory-efficient and can be the better choice for large ranges where creating a whole list isn’t necessary.

Here’s an example:

divisible_numbers = (i for i in range(1, 11) if i % 2 == 0)
for number in divisible_numbers:
    print(number)

Output:

2
4
6
8
10

This snippet creates a generator that defines the same logic as previous methods to identify numbers divisible by 2, and then iterates through this generator to print out each item.

Summary/Discussion

  • Method 1: Basic for-loop. Easy to understand. Not the most efficient for large ranges.
  • Method 2: List Comprehension. Concise and Pythonic. Creates an entire list in memory which may be inefficient for large data sets.
  • Method 3: filter() Function. Functional programming approach. Readable but requires conversion to list to print all at once.
  • Method 4: NumPy. Fast and efficient for large datasets. Overkill for small ranges and requires an external library.
  • Method 5: Generator Expression. Memory-efficient for large ranges. Less intuitive for beginners and slightly more complex to use than list comprehensions.