
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Element-wise Matrix Difference in Python
When it is required to print element wise matrix difference, the list elements are iterated over and the zip method is used on these values.
Example
Below is a demonstration of the same
my_list_1 = [[3, 4, 4], [4, 3, 1], [4, 8, 3]] my_list_2 = [[5, 4, 7], [9, 7, 5], [4, 8, 4]] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_result = [] for sub_str_1, sub_str_2 in zip(my_list_1, my_list_2): temp_str = [] for element_1, element_2 in zip(sub_str_1, sub_str_2): temp_str.append(element_2-element_1) my_result.append(temp_str) print("The result is :") print(my_result)
Output
The first list is : [[3, 4, 4], [4, 3, 1], [4, 8, 3]] The second list is : [[5, 4, 7], [9, 7, 5], [4, 8, 4]] The result is : [[2, 0, 3], [5, 4, 4], [0, 0, 1]]
Explanation
Two list of lists are defined and are displayed on the console.
An empty list is created.
The two list of lists are zipped, using the zip method and iterated over.
Inside the ‘for’ loop, an empty list is created, and the elements of the list of lists are appended to the list.
Outside this, the list is appended to the other list.
This is displayed as output on the console.
Advertisements