hi all,

f1 =
f2 =
f = f1 - f2
i need a output like f = [0.1,0.2,-0.1]

but wen i run this program it is showing error like
TypeError: unsupported operand type(s) for -: 'list' and 'list'


thanks in advance.........

Recommended Answers

All 6 Replies

You have at least two problems:

  1. The types of your list elements are strings.
  2. The list type doesn't have operator minus defined on it

To solve the first problem, just make the list items be floats or whatever: Skip the quotes

To solve the second problem, you can iterate over the lists in a variety of ways.

  • f you understand list comprehension, and the zip function, you could do something like zip the two lists into tuples then subtract tuple at index 1 from the tuple at index 0. I'm not going to give you the answer: Look up list comprehension and the built in function zip However, I will note that I solved your problem with a single short line of code.
  • Another way to do it would be to do something like
    result = []
    for index in range(len(l1):
      # do something useful with l1[index], l2[index] and result

What happens in either case if the lists are not the same length? What should you do about that possibility?

Convert the list values to int/float data type. Then it will be easy to work with them. Eg....

Flist1 = [float(x) for x in f1]
Flist2 =[float(x) for x in f2]

Now you can check for the diff. Btwn the lists.

result = []
for x in len( Flist1):
     result.append(Flist1[x]-Flist2[x])

Coming from my htc phone. Hope you get the idea :)

thanks for a reply

Flist1 = [float(x) for x in f1]
Flist2 =[float(x) for x in f2]
result = []
for x in len( Flist1):
result.append(Flist1[x]-Flist2[x])

wen i run this program it is showing error like:

Traceback (most recent call last):
File "C:/Users/kavya/Desktop/k.py", line 13, in -toplevel-
for x in len( Flist1):
TypeError: iteration over non-sequence

Length is simple number and can not be iterated. You need one function starting with r or x to produce sequence of values.

ow sorry... do this.....

result = []
for x in range(len( Flist1)):
     result.append(Flist1[x]-Flist2[x])

thanks a lot richieking it is working fine........

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.