0

What's the best way to create a list of list which has each value of the first list corresponding to the second list? Like:

a=[1,2,3]
b=[5,6,7]

create c such that:

c=[[1,5][1,6][1,7][2,5][2,6][2,7][3,5][3,6][3,7]]

2 Answers2

3

Best way is to use itertools library.

import itertools
a=[1,2,3]
b=[5,6,7]
c=list(itertools.product(a,b))  

But it makes a list of tuples. If you specifically need a list of lists, you can do

c=[[x, y] for x in a for y in b]
Cihan
  • 2,267
  • 8
  • 19
0
from itertools import product

a = [1, 2, 3]
b = [5, 6, 7]
c = [list(i) for i in product(a, b)]

Value of c:

  [[1, 5], [1, 6], [1, 7], [2, 5], [2, 6], [2, 7], [3, 5], [3, 6], [3, 7]]

itertools.product - From the docs:

Init signature: itertools.product(self, /, *args, **kwargs) Docstring: product(*iterables, repeat=1) --> product object

Cartesian product of input iterables. Equivalent to nested for-loops.

For example, product(A, B) returns the same as: ((x,y) for x in A for y in B). The leftmost iterators are in the outermost for-loop, so the output tuples cycle in a manner similar to an odometer (with the rightmost element changing on every iteration).

To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).

product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2) product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...

Type: type

This solution makes use of a list comprehension

Community
  • 1
  • 1
Totem
  • 7,189
  • 5
  • 39
  • 66