Python subtract two lists

How to subtract two lists in python?

There are several ways to subtract two lists in Python. Here are three methods that you can use:

Method 1: Using a loop to subtract corresponding elements

  • Step 3 — Within the for loop, subtract the element at the current index of list1 from the element at the current index of list2, and append the result to the result list.
result.append(list1[i] - list2[i])
  • Step 4 — After the for loop finishes, the result list will contain the difference between the corresponding elements of the two lists.
list1 = [1, 2, 3] list2 = [4, 5, 6] result = [] for i in range(len(list1)): result.append(list1[i] - list2[i]) print(result)

Method 2: Using a list comprehension to subtract corresponding elements

  • Step 1 — Initialize a list comprehension that will iterate over the elements of the two lists and subtract the corresponding elements.
result = [list1[i] - list2[i] for i in range(len(list1))]
  • Step 2 — The result of the list comprehension will be a new list containing the difference between the corresponding elements of the two lists.
list1 = [1, 2, 3] list2 = [4, 5, 6] result = [list1[i] - list2[i] for i in range(len(list1))] print(result)

Method 3: Using the zip function to subtract corresponding elements

for element1, element2 in zip(list1, list2):
result.append(element1 - element2)
  • Step 3 — After the for loop finishes, the result list will contain the difference between the corresponding elements of the two lists.
list1 = [1, 2, 3] list2 = [4, 5, 6] result = [] for element1, element2 in zip(list1, list2): result.append(element1 - element2) print(result)

Here are a few additional points to consider when subtracting two lists in Python:

  • When using any of the above methods, it is important to ensure that the two lists are of the same length. If the lists have different lengths, you will get an index out of range error when trying to access the elements of the lists using an index.
  • When using the loop method (Method 1) or the zip method (Method 3), you can use the enumerate function to get both the index and the element at each iteration of the loop. This can make the code more readable and allow you to avoid using an index variable (e.g. «i» in the examples above). For example:
for i, (element1, element2) in enumerate(zip(list1, list2)): result.append(element1 - element2)
  • If you want to subtract two lists element-wise, but the lists are not the same length, you can use the itertools.zip_longest function to iterate over the elements in parallel. This function will fill in missing elements with a default value (e.g. None) when one of the lists is exhausted. For example:
from itertools import zip_longest list1 = [1, 2, 3] list2 = [4, 5] result = [] for element1, element2 in zip_longest(list1, list2, fillvalue=0): result.append(element1 - element2) print(result)

Conclusion

To summarize, there are several ways to subtract two lists in Python:

  1. Using a loop to subtract corresponding elements
  2. Using a list comprehension to subtract corresponding elements
  3. Using the zip function to subtract corresponding elements
Читайте также:  Html ширина блока input

It is important to ensure that the two lists are of the same length when using any of these methods. If the lists are not the same length, you can use the itertools.zip_longest function to iterate over the elements in parallel and fill in missing elements with a default value.

I hope this helps you understand how to subtract two lists in Python. Let me know if you have any questions.

Источник

Subtract Two Lists Python

Subtract Two Lists Python | Here we will develop a program to subtract two lists in python. We will give two lists and the python program will subtract these lists using set() and without using set(). We will also develop a python program to subtract lists element by element using built-in function zip() methods and numpy.subtract() methods.

How to subtract two lists in Python:

First take and store two lists, assume we stored them in “a”, and “b” variable, then to substract them use expression: (a – b). Example:-

a = [0, 1, 2, 3, 4, 5,6]b = [0, 2, 5]a-b = [1, 3, 4,6]

How to subtract lists element by element:

a = [10, 15, 20, 30, 40]b = [5, 8, 20, 40, 25]a-b = [5, 7, 0, -10, 15]

Python Subtraction Between Two Lists

We will take two lists while declaring the variables. Then, convert the list to set using set() function and subtract sets. Finally, the subtraction value will be displayed on the screen. The set() function creates a set object. The items in a setlist are unordered, so they will appear in random order.

# Python program to subtract two lists # take list a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [1, 3, 4, 7, 9] # print original list print('list1 =', a) print('list2 =', b) # subtraction of list sub = list(set(a) - set(b)) # print subtraction value print('list1 - list2 =', sub)

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]list2 = [1, 3, 4, 7, 9]list1 – list2 = [8, 2, 5, 6]

Subtract Two arrays

In the previous program, we used the set() function but in this program, we will subtract 2 lists without using the set() function.

# Python program to subtract two lists # take list a = [10, 20, 30, 40, 50, 60, 70, 80, 90] b = [20, 30, 60, 80] # print original list print('list1 =', a) print('list2 =', b) # subtraction of list sub = [i for i in a if not i in b or b.remove(i)] # print subtraction value print('list1 - list2 =', sub)

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90]list2 = [20, 30, 60, 80]list1 – list2 = [10, 40, 50, 70, 90]

Python Subtract Lists Element by Element

In this program, we will give two lists. Then, subtract all elements present in the list and store them in a sub variable using the For Loop. Finally, the subtraction value will be displayed on the screen.

# Python program to subtract lists element by element # take list a = [20, 25, 30, 40, 55, 15] b = [5, 12, 35, 40, 45, 28] # print original list print('list1 =', a) print('list2 =', b) # subtraction of element sub = [] for i in range(len(a)): sub.append(a[i] - b[i]) # print subtraction value print('list1 - list2 =', sub)

list1 = [20, 25, 30, 40, 55, 15]list2 = [5, 12, 35, 40, 45, 28]list1 – list2 = [15, 13, -5, 0, 10, -13]

Читайте также:  If else питон сложные условия

Subtract All Elements in Array

This python program also performs the same task but with different methods. In this program, we are using a built-in function. The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together, etc.

# Python program to subtract lists element by element # take list a = [20, 25, 30, 40, 55, 15] b = [10, 35, 30, 26, 67, 12] # print original list print('list1 =', a) print('list2 =', b) # subtraction of element sub = [x-y for (x, y) in zip(a, b)] # print subtraction value print('list1 - list2 =', sub)

list1 = [20, 25, 30, 40, 55, 15]list2 = [10, 35, 30, 26, 67, 12]list1 – list2 = [10, -10, 0, 14, -12, 3]

Subtract Function in Python

The numpy.subtract() function is used when we want to compute the difference of two numbers or arrays. It returns the difference of numbers.

# Python program to subtract lists element by element # importng numpy.subtract() import numpy # take list a = [10, 14, 8, 64, 54, 47] b = [10, 33, 45, 12, 54, 23] # print original list print('list1 =', a) print('list2 =', b) # subtraction of element sub = numpy.subtract(a, b) # print subtraction value print('list1 - list2 =', sub)

list1 = [10, 14, 8, 64, 54, 47]list2 = [10, 33, 45, 12, 54, 23]list1 – list2 = [0 -19 -37 52 0 24]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

How to Subtract Two Lists in Python

How to Subtract Two Lists in Python

In this tutorial, you’ll learn How to Subtract two lists in Python. Before performing list subtraction, keep in mind that both lists should be of the same length and all the elements should be of the same datatype.

For instance, suppose you have two lists and you want to perform a subtraction between these two lists i.e.,

Input list 1 = [7,6,2,4,-2,8,9] Input list 2 = [2,9,-3,0,9,5,6] Output: Result = [7,6,2,4,-2,8,9] - [2,9,-3,0,9,5,6] = [5,-3,5,4,-11,3,3]

Subtract two Lists in Python

When it comes to subtracting two lists in Python, there are several commonly used methods. One approach is to utilize the zip() function, which pairs corresponding elements from both lists and allows for their subtraction. Another option is to employ list comprehension, which enables concise creation of a new list by subtracting corresponding elements. Additionally, the powerful Numpy library provides the capability to subtract lists by treating them as Numpy arrays. Lastly, a basic for loop can be utilized to subtract elements between two lists iteratively.

1) 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.

# Create and initialize two lists list1 = [9,1,3,7] list2 = [4,4,5,6] #initialize a variable which will store the difference of two lists result = [] for i, j in zip(list1,list2): result.append(i - j) print(result)
  1. An empty list named result is initialized. This list will store the differences between corresponding elements of list1 and list2 .
  2. The zip() the function is used to iterate over the elements of both lists simultaneously. It pairs up the elements at the same index from list1 and list2 .
  3. In each iteration of the loop, the variables i and j receive the corresponding elements from list1 and list2 .
  4. The difference between i and j is calculated using the subtraction operator ( — ), and the result is appended to the result list using the append() method.
  5. After all the iterations are completed, the result the list will contain the differences between the corresponding elements of list1 and list2 .
  6. Finally, the result list is printed to the console using the print() function
Читайте также:  Display money in html

2) Perform Subtraction using List Comprehension

Another way to subtract two lists is by using list comprehension. For this, you need to traverse over the lists and perform subtraction one by one of all elements as shown in the code snippet below.

#create and initialize two lists list1 = [9,1,3] list2 = [4,4,5] #perform subtraction and store the result in "difference" difference = [List1[i]-List2[i] for i in range(min(len(list1), len(List2)))] #print the difference of two lists print(difference)

The provided Python code creates and initializes two lists, list1 and list2 . It then calculates the difference between corresponding elements of the two lists and stores the results in a new list called difference . Finally, it prints the difference list.

3) Difference of Two Lists Using Numpy Array

The previous two methods require traversal over the whole list. One of the simplest methods is to convert the two lists into an array. Here, np.array() function converts two lists into arrays and then uses subtract operator.

#create and initialize two lists list1 = [2,3,9,-4,7] list2 = [4,-1,5,3,8] #convert the two lists into arrays and store the difference difference = np.array(list1)-np.array(list2) #print the difference of two lists print(difference)

4) Using For Loop to Subtract Lists

To subtract two lists in Python using a for loop, you can iterate over the elements of one list and check if each element exists in the other list. If it doesn’t, you can add it to a new list. Here’s an example:

list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] subtracted_list = [] for item in list1: if item not in list2: subtracted_list.append(item) print(subtracted_list)

In the above code, we have two lists list1 and list2. We initialize an empty list subtracted_list to store the result of the subtraction. Next, we iterate over each element in list1 using a for loop. Inside the loop, we check if the current element (item) is present in list2 using the not-in operator. If it’s not found, we append it to the subtracted_list using the append() method. Finally, we print the subtracted_list, which contains the elements that are present in list1 but not in list2. Note that this method assumes that the order of elements in the lists doesn’t matter. If the order matters, you might need to use a different approach, such as list comprehension or set operations.

If you have any queries regarding this article, contact us. Your feedback matters a lot. See more Python Tutorials

Источник

Оцените статью