-1

In one line, how can I generate a list which contains the tuples of all pairs of l1 x l2.

Example: [1,2] et ['a','b'] -> [(1,'a'), (1,'b'), (2,'a'), (2,'b')]

I tried to use map() and zip() but I haven't found the answer yet.

AcK
  • 2,063
  • 2
  • 20
  • 27
Dzung Tran
  • 47
  • 5

3 Answers3

3

you can use itertools.product

from itertools import product
numbers = [1,2]
letters = ['a','b']
result = list(product(numbers,letters))
Nk03
  • 14,699
  • 2
  • 8
  • 22
2

It's as simple as this. Below is an example of a double iteration in listcomprehension.

numbers = [1,2]
letters = ['a','b']
new  = [(num,letter) for num in numbers for letter in letters]

output

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
1

You can use list comprehension.

list3 = [(l1,l2) for l1 in list1 for l2 in list2]
DeMO
  • 153
  • 1
  • 8