Why does itertools.permutations() return a list, instead of a string?

Question:

Why does itertools.permutations() return a list of characters or digits for each permutation, instead of just returning a string?

For example:

>>> print([x for x in itertools.permutations('1234')])
>>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ]

Why doesn’t it return this?

>>> ['1234', '1243', '1324' ... ]
Asked By: kennysong

||

Answers:

itertools.permutations() simply works this way. It takes an arbitrary iterable as an argument, and always returns an iterator yielding tuples. It doesn’t (and shouldn’t) special-case strings. To get a list of strings, you can always join the tuples yourself:

list(map("".join, itertools.permutations('1234')))
Answered By: Sven Marnach

Because it expects an iterable as a parameter and doesn’t know, it’s a string. The parameter is described in the docs.

http://docs.python.org/library/itertools.html#itertools.permutations

Answered By: gruszczy

I have not tried, but most likely should work

comb = itertools.permutations("1234",4)
for x in comb: 
  ''.join(x)    
Answered By: technazi

Perumatation can be done for strings and list also, below is the example..

x = [1,2,3]

if you need to do permutation the above list

print(list(itertools.permutations(x, 2)))

# the above code will give the below..
# [(1,2),(1,3),(2,1)(2,3),(3,1),(3,2)]
Answered By: Sanjay Pradeep
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.