pairwise combination of two lists

Marc Christiansen usenet at solar-empire.de
Wed Aug 17 17:43:44 EDT 2011


Yingjie Lin <Yingjie.Lin at mssm.edu> wrote:
> Hi Python users,
> 
> I have two lists: 
> 
> li1 = ['a', 'b']
> li2 = ['1', '2']
> 
> and I wish to obtain a list like this
> 
> li3 = ['a1', 'a2', 'b1', 'b2']
> 
> Is there a handy and efficient function to do this, especially when
> li1 and li2 are long lists.

Depending on your needs, we can offer you three solutions:

For our customers who want it all at once, but without any unneccessary
waste, the list expression:
[a + b for a, b in itertools.product(li1, li2)]

or if you don't need the whole list at once (especially interesting for
our customers with large lists), the generator expression (genexp):
(a + b for a, b in itertools.product(li1, li2))

and if you don't like the throwaway genexp and want something more
ecofriedly, we can present you a memory efficient, reusable solution, the
generator:
def combiner(li1, li2):
    for a, b in itertools.product(li1, li2):
        yield a + b

;)

HTH, Marc



More information about the Python-list mailing list