In the realm of programming, finding divisors of a number is a fundamental task that often comes up in various algorithms and problem-solving scenarios. Python, with its simplicity and readability, provides an excellent platform to tackle this task. In this article, we will explore two efficient methods to find divisors of a number in Python.
Understanding Divisors
Before we dive into the code, let's quickly recap what divisors are. A divisor of an integer 'n' is an integer that can be multiplied by another integer to produce 'n'. For example, the divisors of 12 are 1, 2, 3, 4, 6, and 12 because 1*12 = 2*6 = 3*4 = 12.
Method 1: Using a For Loop
The first method involves using a simple for loop to iterate through numbers from 1 to the given number and check if the number is divisible. If it is, we add it to our list of divisors.

```python def find_divisors(n): divisors = [] for i in range(1, n + 1): if n % i == 0: divisors.append(i) return divisors ```
This function takes an integer 'n' as input and returns a list of all divisors of 'n'. Here's how you can use it:
```python print(find_divisors(12)) # Output: [1, 2, 3, 4, 6, 12] ```
Method 2: Using List Comprehension
Python's list comprehension provides a more concise way to achieve the same result. This method is particularly useful when you're dealing with large numbers as it's generally faster than using a for loop.
```python def find_divisors(n): return [i for i in range(1, n + 1) if n % i == 0] ```
This function does exactly the same thing as the first method but in a more Pythonic way. Here's how you can use it:

```python print(find_divisors(12)) # Output: [1, 2, 3, 4, 6, 12] ```
Finding Divisors of Large Numbers
When dealing with very large numbers, the above methods might not be the most efficient due to the time complexity of O(n). In such cases, you might want to consider using more advanced algorithms like the Sieve of Eratosthenes or the Quadratic Sieve, which are beyond the scope of this article.
Finding Prime Numbers
As a bonus, you can use the list of divisors to find out if a number is prime. A prime number has exactly two divisors: 1 and itself. So, if the length of the divisors list is 2, the number is prime.
```python def is_prime(n): return len(find_divisors(n)) == 2 ```
This function takes an integer 'n' as input and returns a boolean indicating whether 'n' is a prime number or not.
```python print(is_prime(12)) # Output: False print(is_prime(13)) # Output: True ```
In this article, we've explored two simple yet effective methods to find divisors of a number in Python. Whether you're a seasoned programmer or just starting out, understanding how to find divisors is a crucial skill that will serve you well in your programming journey.