0

I want to print all permutations of length 1-4 for the following list [1,2,3,4]

I know I could just set up a for-loop and pass in the for-loop index as an argument, but I was trying to get the following code to work:

import itertools
nums = [1,2,3,4]
perms = itertools.permutations(nums,range(1,4))
print(list(perms))

The hope was that the argument range(1,4) would run the intertools.permutations(nums) on string lengths 1, 2, 3 and 4.

Any ideas if it is possible to do this using the itertools notation?

Would it also be possible to print the case for length = 1 as: (1), (2), (3), (4) not (1,), (2,), (3,), (4,)

EML
  • 395
  • 1
  • 6
  • 15

2 Answers2

2

Chain together 4 calls of permutations:

from itertools import chain, permutations

nums = [1,2,3,4]
perms = list(chain.from_iterable(permutations(nums, i) for i in range(1,5)))
print(perms)

If you want to print the 1-tuples as individual values, you'll need to handle that separately:

for t in perms:
    if len(t) == 1:
        print("(t[0])")
    else:
        print(t)

That's if you are concerned about the appearance of the tuple. If you truly want a non-tuple value, you'll need to extract the value separately, and keep in mind that 1 and (1) are the exact same value.

perms = list(nums,  # permutations(nums, 1) == nums
             chain.from_iterable(permutations(nums, i) for i in range(2,5)))
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can also write it as a generator expression:

perms = (it for i in range(1, 4) for it in itertools.permutations(nums,i))
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75