-1

Is there a compact way in Python to "multiply" two lists A and B such that every possible combination of elements has some operation applied to it, such that the resulting list has size A*B? I've only found answers in how to combine the nth element of each.

# arguments:
list_x = [a, b, c, d]
list_y = [1, 2, 3, 4]

# returns:
list_xy = [a1, a2, ..., d3, d4]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
frawgs
  • 3
  • 2
  • Are you looking for something like this? [(x, y) for x in list_x for y in list_y] Instead of the (x,y) you could perform your operation. – IsolatedSushi Jan 26 '21 at 11:46
  • 1
    https://docs.python.org/3/library/itertools.html#itertools.product – luthervespers Jan 26 '21 at 11:47
  • "I'm new to python and programming in general so I apologise if this question is phrased wrong." I removed this from the question. It was, in fact, the only thing that was wrong to include. Anyway, the clue is in the verb: when we "mulitply", we get a "product". – Karl Knechtel Feb 18 '23 at 19:30

2 Answers2

1

I think you meant to ask the Cartesian product of the two lists. itertools.product is the thing you are looking for

import itertools
list_xy = [i*j for i,j in itertools.product(list_x,list_y)]
Himanshu Sheoran
  • 1,266
  • 1
  • 6
  • 5
0

if you want to do this only by the use of pure python (no import), you can do it like this:

# arguments:
list_x = ['a', 'b', 'c', 'd']
list_y = ['1', '2', '3', '4']
# returns:
list_xy = [a+b for a in list_x for b in list_y]
print(list_xy)

Output

['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'd3', 'd4']

you may use any other operation instead of a+b.