Python – List Elements Grouping in Matrix

When working with matrices (list of lists), you sometimes need to group elements based on certain criteria. This example demonstrates how to group list elements in a matrix using iteration, the pop() method, list comprehension, and append() methods.

Example

Below is a demonstration of grouping matrix elements ?

my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]

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

check_list = [14, 12, 41, 62]
print("The check list is :")
print(check_list)

my_result = []
while my_list:
    sub_list_1 = my_list.pop()
    
    sub_list_2 = [element for element in check_list if element not in sub_list_1]
    try:
        my_list.remove(sub_list_2)
        my_result.append([sub_list_1, sub_list_2])
    except ValueError:
        my_result.append(sub_list_1)

print("The result is :")
print(my_result)
The list is :
[[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
The check list is :
[14, 12, 41, 62]
The result is :
[[[41, 14], [12, 62]], [78, 87], [51, 23], [14, 62]]

How It Works

The algorithm processes the matrix by ?

  • Popping elements: Remove the last element from my_list and assign it to sub_list_1
  • Finding complement: Create sub_list_2 containing elements from check_list that are not in sub_list_1
  • Grouping logic: If sub_list_2 exists in the remaining matrix, group them together; otherwise, keep sub_list_1 alone
  • Exception handling: Use try-except to handle cases where sub_list_2 is not found in the matrix

Step-by-Step Breakdown

Let's trace through the execution ?

# Initial state
my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
check_list = [14, 12, 41, 62]

# Step 1: Pop [41, 14]
# sub_list_2 = [12, 62] (elements in check_list but not in [41, 14])
# [12, 62] exists in my_list, so group them: [[41, 14], [12, 62]]

# Step 2: Pop [78, 87] 
# sub_list_2 = [14, 12, 41, 62] (none of check_list elements in [78, 87])
# [14, 12, 41, 62] doesn't exist in my_list, so keep [78, 87] alone

print("This demonstrates the grouping logic step by step")
This demonstrates the grouping logic step by step

Conclusion

This approach groups matrix elements by finding complementary sublists based on a reference list. The pop() method processes elements in reverse order, while try-except handling manages cases where no matching complement exists.

Updated on: 2026-03-26T01:15:38+05:30

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements