Python Forum

Full Version: Subtracting Elements of a Sublist in Python 3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am having an issue with subtracting sublists. With the given sublist:

first_list: [[0, 1], [2,4], [8,7]]

There is supposed to be a new list where that contains the difference of the first element from the second element in the sublist:

[-1,-2,-1]

This is the code so far:

for sub_list in data:
differences.append((int(sub_list[1]))-(int(sub_list[0])) in data)

I tried to run this with the other part of the problem to multiply the resulting list, but it fails. It seems to be not iterating. Can anyone offer some suggestions?
from functools import reduce
import operator


# naive way
def sub_list(iterable):
    result = []
    for sub_list in iterable:
        result.append(sub_list[0] - sub_list[1])
    return result

# as list comprehension
def sub_list2(iterable):
    return [sub_list[0] - sub_list[1] for sub_list in iterable]


# with reduce and operator
def sub_list3(iterable):
    return [reduce(operator.sub, sub_list) for sub_list in iterable]


first_list = [[0, 1], [2,4], [8,7]]
The last function allows to have more than two elements in the sublist.
Thank you for getting back to me.
note that your expected output is incorrect and not consistent with your attempt at code
elements with index 0 and 1 are calculated as 0-1 and 2-4, while element with index 2 is calculated as 7-8
in your attempt you do int(sub_list[1])-int(sub_list[0]), so basically if that's correct the output is [1, 2, -1]
>>> spam = [[0, 1], [2,4], [8,7]]
>>> [n2-n1 for n1, n2 in spam]
[1, 2, -1]