Python program to extract rows from Matrix that has distinct data types

When working with matrices containing mixed data types, you may need to extract rows where each element has a distinct data type. This can be achieved by comparing the number of unique types in a row with the total number of elements.

Example

Below is a demonstration of extracting rows with distinct data types ?

my_list = [[4, 2, 6], ["python", 2, {6: 2}], [3, 1, "fun"], [9, (4, 3)]]

print("The list is:")
print(my_list)

my_result = []
for sub in my_list:
    # Get unique data types in the current row
    type_size = len(list(set([type(ele) for ele in sub])))
    
    # If number of unique types equals number of elements
    if len(sub) == type_size:
        my_result.append(sub)

print("The resultant distinct data type rows are:")
print(my_result)
The list is:
[[4, 2, 6], ['python', 2, {6: 2}], [3, 1, 'fun'], [9, (4, 3)]]
The resultant distinct data type rows are:
[['python', 2, {6: 2}], [9, (4, 3)]]

How It Works

The algorithm follows these steps ?

  • Iterate through each row: Loop through every sublist in the matrix
  • Extract data types: Use type(ele) to get the data type of each element
  • Find unique types: Convert to a set to remove duplicate types, then back to a list
  • Compare counts: If the number of unique types equals the row length, all elements have distinct types
  • Collect results: Append qualifying rows to the result list

Alternative Approach

Here's a more concise version using list comprehension ?

my_list = [[4, 2, 6], ["python", 2, {6: 2}], [3, 1, "fun"], [9, (4, 3)]]

print("The list is:")
print(my_list)

# Using list comprehension
my_result = [row for row in my_list 
             if len(row) == len(set(type(ele) for ele in row))]

print("The resultant distinct data type rows are:")
print(my_result)
The list is:
[[4, 2, 6], ['python', 2, {6: 2}], [3, 1, 'fun'], [9, (4, 3)]]
The resultant distinct data type rows are:
[['python', 2, {6: 2}], [9, (4, 3)]]

Conclusion

This technique uses set operations to identify rows with all distinct data types by comparing the count of unique types with the row length. The list comprehension approach provides a more concise solution for the same logic.

Updated on: 2026-03-26T02:55:00+05:30

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements