Python - Merge a Matrix by the Elements of First Column

When it is required to merge a matrix by the elements of first column, a simple iteration and list comprehension with setdefault method is used. This technique groups rows that have the same value in their first column.

Example

Below is a demonstration of the same ?

my_list = [[41, "python"], [13, "pyt"], [41, "is"], [4, "always"], [3, "fun"]]

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

my_result = {}
for key, value in my_list:
    my_result.setdefault(key, []).append(value)

my_result = [[key] + value for key, value in my_result.items()]

print("The result is :")
print(my_result)
The list is :
[[41, 'python'], [13, 'pyt'], [41, 'is'], [4, 'always'], [3, 'fun']]
The result is :
[[41, 'python', 'is'], [13, 'pyt'], [4, 'always'], [3, 'fun']]

How It Works

The algorithm works in two main steps:

  1. Group by first column: Use setdefault() to create a dictionary where keys are first column values and values are lists of corresponding second column values.
  2. Reconstruct matrix: Convert the dictionary back to a matrix format where each row starts with the key followed by all its associated values.

Alternative Using defaultdict

You can also achieve this using defaultdict from the collections module ?

from collections import defaultdict

my_list = [[41, "python"], [13, "pyt"], [41, "is"], [4, "always"], [3, "fun"]]

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

my_result = defaultdict(list)
for key, value in my_list:
    my_result[key].append(value)

my_result = [[key] + value for key, value in my_result.items()]

print("The result is :")
print(my_result)
The list is :
[[41, 'python'], [13, 'pyt'], [41, 'is'], [4, 'always'], [3, 'fun']]
The result is :
[[41, 'python', 'is'], [13, 'pyt'], [4, 'always'], [3, 'fun']]

Conclusion

Matrix merging by first column efficiently groups rows with identical first elements. Use setdefault() for simple cases or defaultdict for cleaner code when working with grouped data structures.

Updated on: 2026-03-26T01:22:42+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements