- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Python Program to find the Next Nearest element in a Matrix

When it is required to find the next nearest element in a matrix, a method is defined tat iterates through the list and places a specific condition. This method is called and the results are displayed.

## Example

Below is a demonstration of the same

def get_nearest_elem(my_list, x, y, my_key): for index, row in enumerate(my_list[x:]): for j, elem in enumerate(row): if elem == my_key and j > y: return index + x, j return -1, -1 my_list = [[21, 32, 11, 22, 13], [91, 52, 31, 26, 33], [81, 52, 3, 22, 3], [11, 92, 83, 4, 9]] print("The list is :") print(my_list) i, j = 1, 3 my_key = 3 my_res_abs,my_res_ord = get_nearest_elem(my_list, i, j, my_key) print("The found K index is :") print(my_res_abs, my_res_ord)

## Output

The list is : [[21, 32, 11, 22, 13], [91, 52, 31, 26, 33], [81, 52, 3, 22, 3], [11, 92, 83, 4, 9]] The found K index is : 2, 4

## Explanation

A method named ‘get_nearest_elem’ is defined that takes a list, a key and two integers as parameters.

The list is iterated over using enumeration and if the element and the key match, the index value summed with the integer is returned.

Outside the method, a list of list is defined and is displayed on the console.

Two integers are defined.

A key value is defined.

The method is called by passing the required parameters.

The output is displayed on the console.

- Related Articles
- Program to find next state of next cell matrix state in Python?
- Program to find the maximum element in a Matrix in C++
- Find next sibling element in Selenium, Python?
- Program to find smallest intersecting element of each row in a matrix in Python
- Program to count elements whose next element also in the array in Python
- Python Program to find the transpose of a matrix
- Python program to remove rows with duplicate element in Matrix
- Find the transpose of a matrix in Python Program
- JavaScript Program to Find maximum element of each row in a matrix
- Program to generate matrix where each cell holds Manhattan distance from nearest 0 in Python
- Python Program to find the largest element in a tuple
- Find the maximum element of each row in a matrix using Python
- Program to find diagonal sum of a matrix in Python
- Program to find the transpose of given matrix in Python
- Python Program to sort rows of a matrix by custom element count

Advertisements