Python – Test if all rows contain any common element with other Matrix

When working with matrices (lists of lists), you might need to check if all corresponding rows share at least one common element. This can be achieved using iteration with a flag variable to track the result.

Example

Below is a demonstration of testing row-wise common elements between two matrices −

matrix_1 = [[3, 16, 1], [2, 4], [4, 31, 31]]
matrix_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]]

print("The first matrix is :")
print(matrix_1)
print("The second matrix is :")
print(matrix_2)

result = True

for idx in range(len(matrix_1)):
    temp = False
    
    for element in matrix_1[idx]:
        if element in matrix_2[idx]:
            temp = True
            break
    
    if not temp:
        result = False
        break

if result:
    print("All rows contain common elements")
else:
    print("Not all rows contain common elements")
The first matrix is :
[[3, 16, 1], [2, 4], [4, 31, 31]]
The second matrix is :
[[42, 16, 12], [42, 8, 12], [31, 7, 10]]
All rows contain common elements

How It Works

  • Two matrices are defined as lists of lists and displayed

  • A result variable is initialized to True

  • For each row index, a temporary flag temp is set to False

  • Each element in the current row of the first matrix is checked against the corresponding row in the second matrix

  • If any common element is found, temp becomes True and the inner loop breaks

  • If no common element is found for any row, result becomes False and the outer loop breaks

  • The final result indicates whether all rows have at least one common element

Alternative Using Set Intersection

A more Pythonic approach uses set intersection −

matrix_1 = [[3, 16, 1], [2, 4], [4, 31, 31]]
matrix_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]]

# Check if all corresponding rows have common elements
result = all(set(matrix_1[i]) & set(matrix_2[i]) for i in range(len(matrix_1)))

if result:
    print("All rows contain common elements")
else:
    print("Not all rows contain common elements")
All rows contain common elements

Conclusion

Use nested loops with flag variables for explicit control, or leverage set intersection with all() for a more concise solution. Both approaches effectively test if all corresponding rows share common elements.

Updated on: 2026-03-26T01:50:08+05:30

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements