-2

I have two lists:

lst1 = ['a', 'b']
lst2 = ['c', 'd', 'e']

I want to make combinations like this:

[['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e']]

Kindly help me with this. Thanks

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Ronnie
  • 391
  • 2
  • 6
  • 19
  • What have you tried so far? Do you need a list of lists or is [an iterable of tuples](https://docs.python.org/3/library/itertools.html#itertools.product) acceptable as well? – MisterMiyagi Jun 28 '20 at 09:55

3 Answers3

1
>>> import itertools
>>> lst1 = ['a', 'b']
>>> lst2 = ['c', 'd', 'e']
>>> itertools.product(lst1, lst2)
<itertools.product object at 0x7f3571488280>
>>> list(itertools.product(lst1, lst2))
[('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e')]
>>> x = list(itertools.product(lst1, lst2))
>>> [list(y) for y in x]
[['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e']]
>>>
frozenOne
  • 558
  • 2
  • 8
0

I leave you an example without using libraries too.

Script:

lst1 = ['a', 'b']
lst2 = ['c', 'd', 'e']
lst3 = []

for item_lst1 in lst1:
    for item_lst2 in lst2:
        lst3.append([item_lst1, item_lst2])

print(lst3)

Output:

[['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e']]
John
  • 770
  • 1
  • 9
  • 18
0

This might do the job for you.

   list1 = ['a', 'b']
   list2 = ['c', 'd', 'e']
    
   req_list = [[x, y] for x in list1 for y in list2]

This type of combining is called cartesian product or cross product.

Surya
  • 971
  • 2
  • 17
  • 30