Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn the result (in python) of itertools.permutations("0123456789") into list of strings

In Python, I am using list(itertools.permutations("0123456789")), and I am receiving (I as expected) a list of tuples of singled character strings.

Is there a way to turn that result into a list of strings, without iterating over all 3628800 items?

like image 958
Matthew Denaburg Avatar asked Mar 17 '11 18:03

Matthew Denaburg


1 Answers

If you want to do it without iterating over the whole list but rather lazily doing it as needed, you can use itertools.imap:

itertools.imap(lambda x: "".join(x), itertools.permutations("0123456789"))

(note that I'm not using list() on the result of permutations here so it's as lazy as possible)

Or, as pointed out in the comments, a simple generator expression would work here as well:

("".join(x) for x in itertools.permutations("0123456789"))

itertools.imap has the additional benefit of being able to apply the same function on lots of iterables with a convenient syntax (simply adding them as subsequent arguments), but that's not necessary for this particular usage as we only have one iterable

like image 170
Daniel DiPaolo Avatar answered Oct 05 '22 06:10

Daniel DiPaolo