Skip to content
Related Articles

Related Articles

Python program to find Successive row difference in Matrix

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 28 Apr, 2022

Given a Matrix, the task is to write a Python program to perform differences from the previous row on the basis of elements present.

Input : test_list = [[5, 6, 3, 1], [7, 5, 3, 1], [3, 2], [7, 3, 3, 2], [2, 3], [9, 8, 1]]

Output : [[], [7], [2], [7], [], [8, 9, 1]]

Explanation : Comparing 1st and 2nd row, only 7 exists in 2nd row and not in 1st hence [7] is output.

Input : test_list = [[5, 6], [7, 5, 3, 1], [3, 4], [7], [2, 9], [9, 8, 1]]

Output : [[], [1, 3, 7], [4], [7], [9, 2], [8, 1]]

Explanation : Comparing 2nd and 3rd list, only 4 is present in 3rd list and not in 2nd, hence output.

Example : Using set.difference() + loop

In this, the previous set is maintained, which keeps the track of the previous set to get the difference. This removes all elements from the current list which are already present in the previous list.

Python3




# Python3 code to demonstrate working of
# Successive row difference in Matrix
# Using set.difference + loop
 
# initializing list
test_list = [[5, 6, 3, 1], [7, 5, 3, 1],
             [3, 2], [7, 3, 3, 2],
             [2, 3], [9, 8, 1]]
              
# printing original list
print("The original list is : " + str(test_list))
 
res = []
prev = set(test_list[0])
for ele in test_list:
     
    # appending difference set diff with previous
    # element
    res.append(list(set(ele).difference(prev)))
     
    # updating prev. for comparison
    prev = set(ele)
 
# printing result
print("Successive Row difference : " + str(res))

Output:

The original list is : [[5, 6, 3, 1], [7, 5, 3, 1], [3, 2], [7, 3, 3, 2], [2, 3], [9, 8, 1]]

Successive Row difference : [[], [7], [2], [7], [], [8, 9, 1]]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!