Skip to main content

How to generate all possible combinations of numbers in Python

How to generate all possible combinations of numbers in Python.

Here's a step-by-step tutorial on how to generate all possible combinations of numbers in Python.

Step 1: Import the itertools module

To generate all possible combinations of numbers, we'll need to use the itertools module in Python. So, the first step is to import this module by adding the following line of code at the beginning of your script:

import itertools

Step 2: Define the input numbers

Next, we need to define the input numbers for which we want to generate the combinations. You can either hardcode the numbers into your code or take user input. For this tutorial, let's assume we have a list of numbers:

numbers = [1, 2, 3]

Step 3: Generate combinations using itertools.combinations()

The itertools module provides a function called combinations() that allows us to generate combinations of elements from an iterable object. In our case, the iterable object is the list of numbers.

To generate all possible combinations of the numbers, we can use a for loop with the combinations() function. Here's an example:

combinations = []
for r in range(1, len(numbers) + 1):
combinations += list(itertools.combinations(numbers, r))

In the above code, we iterate over the range from 1 to the length of the numbers list + 1 (inclusive). This ensures that we generate combinations of all possible lengths from 1 to the total number of elements. For each value of r, we use the combinations() function to generate combinations of length r and append them to the combinations list.

Step 4: Print the generated combinations

Finally, we can print the generated combinations to see the results. Here's an example of how you can print the combinations:

for combination in combinations:
print(combination)

This code will iterate over each combination in the combinations list and print it.

Full Example:

import itertools

numbers = [1, 2, 3]

combinations = []
for r in range(1, len(numbers) + 1):
combinations += list(itertools.combinations(numbers, r))

for combination in combinations:
print(combination)

Running this script will generate and print all possible combinations of the numbers [1, 2, 3]. The output will be:

(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)

That's it! You've successfully generated all possible combinations of numbers in Python using the itertools module.