Search code examples
pythonlistoffset

Offset positive and negative numbers in two lists and get the rest in Python


I have two lists consisting of a series of positive or negative numbers, and two lists may have unequal lengths, like this:

lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]

The result I want to get is:

lst_ofs = [-1, -2, 3, 5, 6, 6, 8, -11]

Positive and negative numbers with equal absolute value in the two lists are offset by quantity, is there any easy way to do this?


Solution

  • result = lst1 + lst2
    # keep checking for pairs until none are left
    while True:
        for v in result:
            if -v in result:
                # if v and -v are in the list, remove them both
                # and restart the for loop
                result.remove(v)
                result.remove(-v)
                break
        else:
            # if the for loop made it all the way to the end,
            # break the outer loop
            break
    

    This isn't the most efficient solution, because the for loop starts over each time two values are removed. But it should work.