pairwise combination of two lists

Ned Deily nad at acm.org
Wed Aug 17 17:33:17 EDT 2011


In article <98CC6556-11F3-4850-BD2B-30481B53042D at mssm.edu>,
 Yingjie Lin <Yingjie.Lin at mssm.edu> wrote:
> 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.
> I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly what I 
> am looking for.

>>> from itertools import product
>>> li1 = ['a', 'b']
>>> li2 = ['1', '2']
>>> li3 = list("".join(x) for x in product(li1, li2))
>>> li3
['a1', 'a2', 'b1', 'b2']

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list