Combinations or Permutations

Raymond Hettinger python at rcn.com
Tue Sep 21 15:41:40 EDT 2010


On Sep 20, 1:54 pm, Seth Leija <fazzit... at gmail.com> wrote:
> I need to know how to generate a list of combinations/permutations
> (can't remember which it is). Say I have a list of variables:
>
> [a,b,c,d,...,x,y,z]
>
> I am curious if there is an optimized way to generate this:
>
> [[a,b],[a,c],[a,d],...,[x,z],[y,z]]

Try this:

>>> from itertools import combinations
>>> list(combinations('abcde', 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b',
'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e')]


Raymond



More information about the Python-list mailing list