-4
a=[[1,2],[3,4,5],[4,5]]
b=[[2,3],[4,5,6],[5,6]]
b-a

Excpected Output[[1,1],[1,1,1],[1,1]]

I am trying to do a difference between these two lists, but I am getting the error.

for i in a:
  for j in b:
    i-j

TypeError                                 Traceback (most recent call last)
<ipython-input-27-c822a6dc04a2> in <module>()
      1 for i in a:
      2   for j in b:
----> 3     i-j

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Can anyone help me with this?

Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 1
    Similar to https://stackoverflow.com/q/11677860/7954504, but with nested lists here – Brad Solomon Nov 12 '20 at 14:57
  • Yeah but I'm not able to figure out how to do with the nested lists as I'm new to python, it would be grateful if anyone has helped to solve this!! – Srihasa Vejendla Nov 12 '20 at 15:04
  • See also [How to perform element-wise arithmetic operations (e.g. add, subtract, multiply) of two equally shaped lists with arbitrary nestings](https://stackoverflow.com/q/57615420/7851470) – Georgy Nov 12 '20 at 15:17

3 Answers3

1

You can do this with a simple nested list comprehension and zip()

a = [[1,2],[3,4,5],[4,5]]
b = [[2,3],[4,5,6],[5,6]]

difs = [[n2 - n1 for n1, n2 in zip(l1, l2)] for l1, l2 in zip(a, b)]
# [[1, 1], [1, 1, 1], [1, 1]]

zip() is made especially for pairing off elements like this. First you pair off the matching lists with zip(a, b) then for each item in those pairs you pair off the numbers with zip(l1, l2).

Like all list comprehensions you can of course do this as a nested for loop:

a = [[1,2],[3,4,5],[4,5]]
b = [[2,3],[4,5,6],[5,6]]

l = []

for l1, l2 in zip(a, b):
    current = []
    for n1, n2 in zip(l1, l2):
        current.append(n2 - n1)
    l.append(current)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

This can be done using a nested while loop like so:

a=[[1,2],[3,4,5],[4,5]]
b=[[2,3],[4,5,6],[5,6]]

i = 0
difference_list = []
while i < len(a):
    difference_list.append([])
    j = 0
    while j < len(a[i]):
        difference_list[i].append(b[i][j] - a[i][j])
        j += 1
    i += 1

Giving the following output:

[[1, 1], [1, 1, 1], [1, 1]]
ChaddRobertson
  • 605
  • 3
  • 11
  • 30
0

You can do using nested list comprehensions. Inner one provides a difference list between two lists and the outer one loops it through list of lists.

a = [[1,2],[3,4,5],[4,5]]
b = [[2,3],[4,5,6],[5,6]]
    
c = [[y-x for x,y in zip(list_a, list_b)] for list_a, list_b in zip(a,b)]
c
[[1, 1], [1, 1, 1], [1, 1]]
Murali
  • 154
  • 1
  • 12