0

Say you have 2 lists of unique values, how can you create a list/dataframe/array with a record for each value.

list_1 = [1, 2, 3, 4]
list_2 = ['one', 'two', 'three', 'four']

expected = [
    [1, 'one'],
    [2, 'one'],
    [3, 'one'],
    [4, 'one'],
    ...
    [1, 'four'],
    [2, 'four'],
    [3, 'four'],
    [4, 'four']
]
bdoubleu
  • 5,568
  • 2
  • 20
  • 53
  • 2
    `list(itertools.product(list_1,list_2)) ` – BENY Sep 28 '18 at 18:02
  • 1
    I recommend using the Pandorable / Numpythonic solution [here](https://stackoverflow.com/a/25636395/9209546) in the dup. – jpp Sep 28 '18 at 18:06

1 Answers1

1

You could use list comprehension:

[[i,j] for i in list_1 for j in list_2]

Output:

[[1, 'one'],
 [1, 'two'],
 [1, 'three'],
 [1, 'four'],
 [2, 'one'],
 [2, 'two'],
 [2, 'three'],
 [2, 'four'],
 [3, 'one'],
 [3, 'two'],
 [3, 'three'],
 [3, 'four'],
 [4, 'one'],
 [4, 'two'],
 [4, 'three'],
 [4, 'four']]

Or you could use itertools.product to get a list of tuples:

import itertools
list(itertools.product(list_1, list_2))

Output:

[(1, 'one'),
 (1, 'two'),
 (1, 'three'),
 (1, 'four'),
 (2, 'one'),
 (2, 'two'),
 (2, 'three'),
 (2, 'four'),
 (3, 'one'),
 (3, 'two'),
 (3, 'three'),
 (3, 'four'),
 (4, 'one'),
 (4, 'two'),
 (4, 'three'),
 (4, 'four')]
Joe Patten
  • 1,664
  • 1
  • 9
  • 15