-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
  • 1,870
  • 1
  • 17
  • 22
Dzung Tran
  • 29
  • 4

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,136
  • 2
  • 6
  • 20
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')]
Thavas Antonio
  • 5,542
  • 1
  • 11
  • 33
1

You can use list comprehension.

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