Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of combinations

I would like to create a list of numbers with three values and would like to cover every combination from 0 - 3. For example:

0, 0, 0
0, 0, 1
...
1, 0, 3
1, 1, 3

all the way to 3, 3, 3.

Is there a better way to do this than using multiple for loops?

Here is the code that I used:

for i in range (0, 4):
    for x in range (0, 4):
        for t in range (0, 4):
        assign = [i, x, t]
like image 314
Eric Zajac Avatar asked Jan 01 '26 14:01

Eric Zajac


2 Answers

Usually itertools.product:

list(itertools.product(range(4), repeat=3))

like image 185
wim Avatar answered Jan 03 '26 03:01

wim


You can use the itertools.product() function for that:

from itertools import product

for i, x, t in product(range(4), repeat=3):
    print (i, x, t)

Demo:

>>> from itertools import product
>>> for i, x, t in product(range(4), repeat=3):
...     print (i, x, t)
... 
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
(0, 1, 0)
# ... truncated for readability ...
(3, 2, 3)
(3, 3, 0)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)
like image 29
Martijn Pieters Avatar answered Jan 03 '26 04:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!