0

I am currently trying to cross join two lists with addition and I'm not entirely sure how to do that.

Suppose I have to two lists:

list1 = [5,2,8]
list2 = [11,6,3]
sum_list = []

my expected output would be:

print (sum_list)

Output
[16,11,8,13,8,5,19,14,11]
  • You can iterate through one array and with each value of this array you sum element of the second array. Basically a for loop into a for loop (most easy to understand and way to do it but not the most optimized) – El Pandario May 09 '22 at 12:47

1 Answers1

0
sum_list= [x+y for x in list1 for y in list2]

It is just the nested loops.

Or

for x in list1:
  for y in list2:
    sum_list.append(x+y)

#output
[16, 11, 8, 13, 8, 5, 19, 14, 11]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • Suppose both lists were 2D how would the loop work then? For example list1 =( [5,2,8],[1,2,3]) list2 = ([11,6,3], [1,2,3]) – dfsfs fdsfsd May 09 '22 at 14:39
  • You can flatten both the lists by `sum(list1, [])` and `sum(list2, [])`. Then apply the above mentioned answer on them. This way of flattening the list is very inefficient but, you can use it on small lists. You can find other ways to flatten lists here https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists – Talha Tayyab May 09 '22 at 15:45