0
from itertools import permutations
l = [0, 1, 2, 3, 4]
x = permutations (l, 3)

I get the following :

(0, 1, 2) , (0, 1, 3), ...., (0, 2, 1), (0, 2, 3), (0,2,4),...., (4, 3, 0), (4, 3, 1),
(4, 3, 2)

Which is what was expected. But what i need is :

(0, 0, 0), (0, 0, 1), ...., (0, 0, 4), (0, 1, 0), (0, 1, 1)........

How to achieve this ?

  • You did not explain what the result should contain. But check the other functions in itertools to see if one fits your needs. – Klaus D. Jun 03 '17 at 03:12

3 Answers3

2

What you need is a permutation with replacement, or a product, but itertool's permutations produces permutations without replacement. You can calculate the product yourself:

[(x,y,z) for x in l for y in l for z in l]
#[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), ...

Or use the namesake function from itertools:

list(itertools.product(l,repeat=3))
# [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0),...

The latter approach is more efficient.

DYZ
  • 55,249
  • 10
  • 64
  • 93
1

You need to use product , not using permutations, from itertools module like this example:

from itertools import product

l = [0, 1, 2, 3, 4]
# Or:
# b = list(product(l, repeat=3))
b = list(product(l,l,l))
print(b)

Output:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), ..., (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4)]
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
0

You need product and not permutation

from itertools import product
l = [0, 1, 2, 3, 4]
b = list(product(l, repeat=3))
Eds_k
  • 944
  • 10
  • 12