Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting 2 lists in Python

Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like

[2,2,2] - [1,1,1] = [1,1,1] 

Should I use tuples?

If none of them defines these operands on these types, can I define it instead?

If not, should I create a new vector3 class?

like image 825
Joan Venge Avatar asked Feb 10 '09 23:02

Joan Venge


People also ask

How do you subtract between two lists?

subtract two lists using Zip() Function In this method, we'll pass the two input lists to the Zip Function. Then, iterate over the zip object using for loop. On every iteration, the program will take an element from list1 and list2, subtract them and append the result into another list.

Can you subtract a list from another list in Python?

Method 3: Use a list comprehension and set to Find the Difference Between Two Lists in Python. In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator.

How do you subtract two lists in NumPy?

subtract() in Python. numpy. subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.


1 Answers

If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy.

Otherwise, look for list comprehensions used with the zip builtin function:

[a_i - b_i for a_i, b_i in zip(a, b)] 
like image 154
UncleZeiv Avatar answered Sep 22 '22 17:09

UncleZeiv