0

Suppose there are two lists:

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

what I want is:

'ad','ae','af','bd','be','bf','cd','ce','cf'


 first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
combined_list = []
for i in first_list:
    for j in second_list:
        combined_list.append(i + j)
print(combined_list)

my question is if there are not only two lists, how to improve the code? for example,

first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
print ['adg','adh','adq','aeg','aeh',.......]

guys,are there any generalizable ways to show n lists..I mean what if there are more than three lists?

Linda dadad
  • 97
  • 1
  • 6

2 Answers2

2

This is called a cartesian product.

import itertools

first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
lists = [first_list, second_list, third_list]

cartesian_product = [''.join(x) for x in itertools.product(*lists)]

print(cartesian_product)

Output:

['adg', 'adh', 'adq', 'aeg', 'aeh', 'aeq', 'afg', 'afh', 'afq',
 'bdg', 'bdh', 'bdq', 'beg', 'beh', 'beq', 'bfg', 'bfh', 'bfq',
 'cdg', 'cdh', 'cdq', 'ceg', 'ceh', 'ceq', 'cfg', 'cfh', 'cfq']

You can try it online, here.

Here's an example implementation of a cartesian production function, which you can try out here.

def cartesian_product(*lists):
    if not lists: # base case
        return [[]]
    else:
        this_list = lists[0]
        remaining_lists = lists[1:]
        return [
          [x] + p
            for x in this_list
              for p in cartesian_product(*remaining_lists)
        ]
Alexander
  • 59,041
  • 12
  • 98
  • 151
0

I haven't tested this but this should work.

first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
combined_list = []
for i in first_list:
    for j in second_list:
        for k in third_list:
            combined_list.append(i + j + k)
print(combined_list)
user82395214
  • 829
  • 14
  • 37