Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Row with Minimum element in Matrix
Next article icon

Search Elements in a Matrix – Python

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]], the task would be to check if an element like 13 is present. The result would be True if found, or False if the element does not exist within the matrix.

Using list comprehension

any() is a built-in Python function that checks if any element in an iterable evaluates to True. When combined with list comprehension, it allows us to check if an element exists in any of the sublists in a nested list or matrix .

Python
a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]]  res = any(13 in sub for sub in a) print(str(res)) 

Output
True 

Explanation: any(13 in sub for sub in a) checks if 13 is present in any row of the matrix a. It uses a generator expression with any(), which returns True as soon as 13 is found.

Using numpy

NumPy is a powerful library for numerical computations . It provides a highly efficient way to work with large matrices due to vectorized operations. This eliminates the need for explicit loops, making operations faster and easier to write.

Python
import numpy as np  # Create a 2D NumPy array  a = np.array([[4, 5, 6], [10, 2, 13], [1, 11, 18]])  res = np.any(a == 13) print(res) 

Output
True 

Explanation: np.any(a == 13) checks if 13 exists in the NumPy array a. The expression (a == 13) creates a boolean array and np.any() returns True if at least one True value is found, ensuring an efficient search.

Using itertools.chain

itertools.chain function from itertools module that takes multiple iterables and combines them into a single iterable. This is useful when we want to flatten a matrix and perform operations on all elements without explicitly nesting loops.

Python
import itertools a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]]  res = 19 in itertools.chain(*a) print(str(res)) 

Output
False 

Explanation: 19 in itertools.chain(*a) flattens the 2D list a and checks if 19 is present in the flattened sequence, offering a efficient way to search for the element.

Using for loop

This is the most explicit method, where we manually iterate through the matrix using a nested for loop. It checks each row to see if the target element is present and exits early once a match is found.

Python
a = [[4, 5, 6], [10, 2, 13], [1, 11, 18]] found = False # Initialize a variable 'found'  for row in a:     if 19 in row:         found = True         break print(str(found)) 

Output
False 

Explanation: for loop iterates through each row of the matrix a. If 19 is found in a row, found is set to True and the loop exits early with break.



Next Article
Python | Row with Minimum element in Matrix
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Marketing
  • Python list-programs
  • Python matrix-program
Practice Tags :
  • python

Similar Reads

  • Python - Check Similar elements in Matrix rows
    Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of the List. Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : True Explanation : All rows have same elements.Input : test_list = [[1, 1,
    8 min read
  • Python | Search in Nth Column of Matrix
    Sometimes, while working with Python Matrix, we can have a problem in which we need to check if an element is present or not. This problem is simpler, but a variation to it can be to perform a check in a particular column of Matrix. Let's discuss a shorthand by which this task can be performed. Meth
    10 min read
  • Python | Row with Minimum element in Matrix
    We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but sometimes we need to print the entire row containing it and having shorthands to perform the same are always helpful as this kind of problem can come
    5 min read
  • Python - Flag None Element Rows in Matrix
    Given a Matrix, return True for rows which contain a None Value, else return False. Input : test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8, None]] Output : [True, True, False, True] Explanation : 1, 2 and 4th index contain None occurrence. Input : test_list = [[2, 4, None, 3], [3
    4 min read
  • Linear Search - Python
    Given an array, arr of n elements, and an element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesn’t exist. Examples: Input: arr[] = [10, 50, 30, 70, 80, 20, 90, 40], x = 30Output : 2Explanation: For array [10, 50, 30, 7
    4 min read
  • Find element in Array - Python
    Finding an item in an array in Python can be done using several different methods depending on the situation. Here are a few of the most common ways to find an item in a Python array. Using the in Operatorin operator is one of the most straightforward ways to check if an item exists in an array. It
    3 min read
  • Python - Rows with all List elements
    Given a Matrix, get all the rows with all the list elements. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [1, 2] Output : [[2, 1, 8], [6, 1, 2]] Explanation : Extracted lists have 1 and 2. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [2
    8 min read
  • Python | Remove similar element rows in tuple Matrix
    Sometimes, while working with data, we can have a problem in which we need to remove elements from the tuple matrix on a condition that if all elements in row of tuple matrix is same. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + all() This ta
    6 min read
  • Binary Search (bisect) in Python
    Binary Search is a technique used to search element in a sorted list. In this article, we will looking at library functions to do Binary Search.Finding first occurrence of an element. bisect.bisect_left(a, x, lo=0, hi=len(a)) : Returns leftmost insertion point of x in a sorted list. Last two paramet
    2 min read
  • Python - Retain all K elements Rows
    Sometimes, while working with Python lists, we can have a problem in which we need to retain rows which have only K as elements. This kind of application can occur in data domains which take Matrix as input. Let's discuss certain ways in which this task can be performed. Input : test_list = [[7, 6],
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences