- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 - Print rows from the matrix that have same element at a given index
When it is required to print the rows from the matrix that have the same element at the given index, a list comprehension and the ‘all’ operator is used.
Below is a demonstration of the same −
Example
my_list = [[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]] print("The list is :") print(my_list) my_key = 1 print("The key is ") print(my_key) my_result = [element for element in my_list if all(str(i)[my_key] == str(element[0])[my_key] for i in element)] print("The result is :") print(my_result)
Output
The list is : [[7745, 6755, 87, 978], [727, 927, 845], [192, 997, 49], [98, 74, 27]] The key is 1 The result is : [[7745, 6755, 87, 978], [192, 997, 49]]
Explanation
A list of list is defined and is displayed on the console.
The value for key is defined and displayed on the console.
A list comprehension is used to iterate over the list, and the ‘all’ operator is used to check if a specific element at an index is equal to the key.
This is converted to a list and is assigned to a variable.
This is displayed as output on the console.
Advertisements