0

I have some lists

a = [1,2]
b = [A,B]

I want to generate a new list of lists similar to the following (I don't remeber the name of this "operation"...)

[1,A],[1,B],[2,A],[2,B]

Is there a rapid way to achieve this result?

Chris Cris
  • 215
  • 3
  • 13

1 Answers1

2

Its what that itertools.product is for :

>>> from itertools import product
>>> 
>>> a = [1,2]
>>> b = ['A','B']
>>> 
>>> list(product(a,b))
[(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]

And if you want the result to be a nested list you can use map function to convert the tuples to list :

>>> map(list,product(a,b))
[[1, 'A'], [1, 'B'], [2, 'A'], [2, 'B']]
Mazdak
  • 105,000
  • 18
  • 159
  • 188