
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Python – Test if all rows contain any common element with other Matrix
When it is required to test if all rows contain any common element with other matrix, a simple iteration and a flag value are used.
Example
Below is a demonstration of the same
my_list_1 = [[3, 16, 1], [2, 4], [4, 31, 31]] my_list_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_result = True for idx in range(0, len(my_list_1)): temp = False for element in my_list_1[idx]: if element in my_list_2[idx]: temp = True break if not temp : my_result = False break if(temp == True): print("The two matrices contain common elements") else: print("The two matrices don't contain common elements")
Output
The first list is : [[3, 16, 1], [2, 4], [4, 31, 31]] The second list is : [[42, 16, 12], [42, 8, 12], [31, 7, 10]] The two matrices don't contain common elements
Explanation
Two lists of lists are defined and are displayed on the console.
A variable is set to Boolean ‘True’.
The first list is iterated and a temporary variable is set to Boolean ‘False’.
If the element is present in the second list, then the temporary variable is set to Boolean ‘True’.
The control breaks out of the loop.
If the temporary variable is False outside the loop, the control breaks out of the loop.
In the end, based on the value of the temporary variable, the relevant message is displayed on the console.
- Related Articles
- Check if all rows of a matrix are circular rotations of each other in Python
- Find distinct elements common to all rows of a matrix in Python
- Python - Check if two lists have any element in common
- Python Program to Test if any set element exists in List
- Find a common element in all rows of a given row-wise sorted matrix in C++
- Python program to remove rows with duplicate element in Matrix
- Find Smallest Common Element in All Rows in C++
- Python – Test if all elements are unique in columns of a Matrix
- Python – Test if Rows have Similar frequency
- Find distinct elements common to all rows of a Matrix in C++
- Remove similar element rows in tuple Matrix in Python
- Python – Rows with K string in Matrix
- Does this array contain any majority element - JavaScript
- How to remove rows that contain NAs in R matrix?
- Python – Rows with all List elements

Advertisements