I am new to Python and am trying out itertools
:
import itertools as it
obj = it.permutations(range(4))
print(obj)
for perm in obj:
print( perm )
My Question: How do I view/print all the permutations in obj
directly without using a for
loop?
What I Tried:
I tried using __dict__
and vars
as suggested in this SO link but both do not work (former does not seem to exist for the object while latter generated 'TypeError: 'itertools.permutations' object is not callable').
Please pardon if my question is rather noobish - this attributes issue appears complicated and most of what is written in SO link flew over my head.
Just cast your obj
to a list
:
print(list(obj))
This will give you the following output:
[(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2), (0, 3, 2, 1), (1, 0, 2, 3), (1, 0, 3, 2), (1, 2, 0, 3), (1, 2, 3, 0), (1, 3, 0, 2), (1, 3, 2, 0), (2, 0, 1, 3), (2, 0, 3, 1), (2, 1, 0, 3), (2, 1, 3, 0), (2, 3, 0, 1), (2, 3, 1, 0), (3, 0, 1, 2), (3, 0, 2, 1), (3, 1, 0, 2), (3, 1, 2, 0), (3, 2, 0, 1), (3, 2, 1, 0)]
That's the direct answer to your question. Another good thing to figure out is whether you really need what you are asking for.
You see, there is a reason why permutations
returns a generator. If you ain't familiar with that pattern, I'd strongly suggest reading about it. To make a long story short, generally you don't wanna cast such things to a list
unless you really need it to be a list
(e.g. you want to access items directly by index). In your case where you only need to print permutations there is absolutely nothing wrong with using for
loop.
Here is one-liner to print one permutation per line:
print('\n'.join(str(permutation) for permutation in obj))
But again, simple for
loop which you are using already is just fine. Remember that simple is better than complex.