Python Learner
Python Learner

Reputation: 11

I want to simply subtract elements from two lists

I have two open lists. First Weight (fWeight) and Second Weight (sWeight). I want to subtract the fWeight from sWeight. I am getting this error:

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

Is there a a simple solution for this?

names_array = list()
firstWeight_Array=list()
students = 2
for i in range(students):
    name = str(raw_input("Please enter a  name:"))
    names_array.append(str(name))
    fWeight = int(raw_input("Please enter the first weight:"))
    firstWeight_Array.append(int(fWeight))

SecondWeight_Array=list()
for i in range(students):
        sWeight = int(raw_input("Please enter the Second weight:"))
        SecondWeight_Array.append(int(sWeight))

print(firstWeight_Array,SecondWeight_Array)
print firstWeight_Array - SecondWeight_Array

Upvotes: 0

Views: 1753

Answers (3)

SomethingSomething
SomethingSomething

Reputation: 12178

I would do:

diffs = [firstWeight_Array[i] - secondWeight_Array[i] for i in xrange(len(students))]

In case that you work with Python 3, use range instead of xrange

Upvotes: 0

meskobalazs
meskobalazs

Reputation: 16041

The substraction operator is not defined for list, as it makes no sense in a general way. However, you can simply get the single items using the [] operator, and calculate the difference in a new list:

newArray = list();
for i in xrange(students):
    newArray.append(firstWeight_Array[i] - secondWeight_Array[i]);
print newArray;

Upvotes: 1

Sylvain Leroux
Sylvain Leroux

Reputation: 51990

If you need to subtract every item from one list to the corresponding item of a second list of same size, the easiest way (and probably the most idiomatic way) is to use a list comprehension and the zip function:

diff = [first - second 
        for first, second in zip(firstWeight_Array, secondWeight_Array)]

Here is a simple example:

>>> firstWeight_Array = [10,20,30]
>>> secondWeight_Array = [12,18,34]

>>> diff = [first - second 
...         for first, second in zip(firstWeight_Array, secondWeight_Array)]

>>> diff
[-2, 2, -4]

Please note that for space efficiency reason, in Python 2, you might prefer using itertools.izip instead of a plain zip.

Upvotes: 1

Related Questions