list of all possible values

Andreas Tawn andreas.tawn at
Thu Jul 16 18:49:11 CEST 2009

> > Certainly possible with list comprehensions.
> >
> >>>> a = "abc"
> >>>> [(x, y) for x in a for y in a]
> > [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b',
> > ('c', 'a'), ('c', 'b'), ('c', 'c')]
> >
> > But I like bearophile's version better.
> >
> Andreas,
> Thanks, but I think you were missing my point. I should have explained
> The advantage that bearophile's version is generic with respect to the
> number of elements in each combination. To go from 2 element pairs
> (e.g. ('a', 'c')) to 5 element pairs (e.g. ('a', 'c', 'b', 'b', 'e'))
> requires only a change in a parameter passed to itertools.
> I don't see how you would do that with list comprehensions. You're
> example works nicely with 2 element pairs, but it seems to me like
> you'd need to recode it if you wanted to change it to 5 element pairs.
> Am I wrong about that? Can you think of a way to write a function
> that, using list comprehensions, takes a list of values and the size
> of each combination, and returns the len(list)**(combination size)
> possible combinations using those values?
> Thanks again,
> David


I think my post got caught in the nebulous email eddys and seems to have
taken 16 hours to arrive on the list. It was meant to be a reply to your
first post, not your second.

Having said that, I think I missed the point of that post too ;o)

Maybe someone smarter than me can come up with a way to dynamically nest
the fors in a list comprehension, but I certainly can't do it.

Sorry for the confusion.



More information about the Python-list mailing list