- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 and ‘setdefault’ method is used.

## 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)

## Output

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']]

## Explanation

A list is defined and displayed on the console.

An empty dictionary is created.

The list is iterated over, and the key-value pair with same keys are joined together and appended to the dictionary.

A list comprehension is used to get the elements of the dictionary, and the key and the value are added.

This is assigned to a variable.

This is the output that is displayed on the console.

- Related Questions & Answers
- Python Program to Remove First Diagonal Elements from a Square Matrix
- Column Sort of a Matrix in Python
- How to select a column of a matrix by column name in R?
- Find sum of all elements in a matrix except the elements in row and-or column of given cell in Python
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- How to find the mean of a square matrix elements by excluding diagonal elements in R?
- How to group Python tuple elements by their first element?
- Filter column value by the first character in MySQL
- Spiraling the elements of a square matrix JavaScript
- Get Nth Column of Matrix in Python
- Python – Sort Matrix by Number of elements greater than its previous element
- How to divide columns of a matrix by vector elements in R?
- Java Program to Interchange Elements of First and Last in a Matrix Across Rows
- Java Program to Interchange Elements of First and Last in a Matrix Across Columns
- Program to find number of elements in matrix follows row column criteria in Python

Advertisements