-1

For example:

X = [1, 3]
Y = [-1, 1, 0]

The output should be like this:

[-1, 1, 0, -3, 3, 0]

Is there a way to do this and also for other calculations such as summation. I searched over here and internet but I could not find any solution.

Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
Nisa Aslan
  • 35
  • 3
  • 2
    I think you just want `[x*y for x in X for y in Y]` – juanpa.arrivillaga May 24 '21 at 18:42
  • Welcome to Stack Overflow. From the example what you want is a [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product) -in other words a Cartesian product- for each element of the smallest list. This can be done in several ways, using list comprehensions or nested for loops. One way would be like in [this example](https://stackoverflow.com/a/49899275) once for each element of the smaller list. Also see [the search function](https://stackoverflow.com/help/searching). Here [one search example](https://stackoverflow.com/search?q=%5Bpython%5D+vector+product+list) – bad_coder May 24 '21 at 23:45
  • 1
    Regarding the summing you mentioned in the question, you have this: [Fastest way to sum values every combination of multiple lists in Python](https://stackoverflow.com/q/47996986/6045800) – Tomerikoo May 25 '21 at 08:44

2 Answers2

1

i think that's what you need.

X = [1,3]
Y = [-1,1,0]

res = [x*y for x in X for y in Y]
print(res)
imerla
  • 1,496
  • 2
  • 12
  • 18
1

As an alternative to list comprehension solution that mentioned by others, product in itertools module, does the same iteration pattern as two nested loops in case you need to work with other iterators in chain or performance matters for large amount of data :

from itertools import product

X = [1, 3]
Y = [-1, 1, 0]

res = [i * j for i, j in product(X, Y)]

print(res)
S.B
  • 7,457
  • 5
  • 15
  • 37