0

I would like to write all the permutations of 6 into blocks of 4. When I do the print(template) it actually prints the desired permutation: Permutations work fine as seen on the image

However when I append them to the big_template and print the big_template (which I want to contain a list of all the permutations) all it prints is a list of [6,6,6,6].

Big_template is not as expected

Here is my code:

template = ['' for i in range(4)]
big_template = []
j=0
for i in range(1,7):
    template[j]=i
    for i in range(1,7):
        template[j+1]=i
        for i in range(1,7):
            template[j+2]=i
            for i in range(1,7):
                template[j+3]=i
                print(template)
                big_template.append(template)
print(big_template)

My question is what I am doing wrong. Also I would like to extend this procedure to permutations of 6 in any number box. By my method I would have as many for loops as entries into the box. How can this be done using recursion functions?

Cheers.

MystMan
  • 23
  • 1
  • 4
  • 1
    You should consider using the [itertools permutation function](https://docs.python.org/3.6/library/itertools.html#itertools.permutations) – Grant Williams Apr 09 '18 at 14:24

1 Answers1

0

Consider using methods from itertools, such as permutation.

In your example, each element of big_template is the same object, template, as you can see using the is operator.

print(big_template[0] is template)
print(big_template[0] is big_template[1])

will both yield True. This explains why big_template only containts [6,6,6,6], which is the last value taken by template.

See Python initializing a list of lists for example, for more in this topic.

To make your code work as it is, you should call copy: big_template.append(template.copy()).

But you really should use permutation instead.

Tttt1228
  • 409
  • 5
  • 11