Best way to handle boundary check for 2D list in python?

I have one 2D list like following, I want to change cell value from 1 to 0 if the cell surrounding cell is 0 like

from
[
  [1, 0, 1, 0, 1],
  [0, 0, 1, 0, 0],
  [0, 0, 0, 0, 0],
  [1, 0, 1, 0, 1],
  [0, 0, 0, 0, 0],
  [1, 0, 1, 0, 1],
]
To
[
  [0, 0, 1, 0, 0],
  [0, 0, 1, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
]

I think I can use 8 if/else logic to check but wondering if there is a better or clean way to do it?

I will make use of python generator to get the valid neighbors, and use the all to check if all the neighbors are zero.

def update_cell(grid):
    if not grid or not grid[0]:
        return
    m, n = len(grid), len(grid[0])

    def is_valid(i, j):
        return 0 <= i < m and 0 <= j < n

    def neighbors(i, j):
        for di, dj in [(0, 1), (0, -1), (1, 0), (-1, 0), (-1, 1), (-1, -1), (1, -1), (1, 1)]:
            ni, nj = i+di, j+dj
            if is_valid(ni, nj):
                yield ni, nj

    for i in range(m):
        for j in range(n):
            if grid[i][j] and all(not grid[ni][nj] for ni, nj in neighbors(i, j)):
                grid[i][j] = 0


if __name__ == "__main__":

    grid = [
        [1, 0, 1, 0, 1],
        [0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 0, 1, 0, 1],
        [0, 0, 0, 0, 0],
        [1, 0, 1, 0, 1],
    ]

    update_cell(grid)

    print(grid)

   # prints
   #[[0, 0, 1, 0, 0], 
   # [0, 0, 1, 0, 0], 
   # [0, 0, 0, 0, 0], 
   # [0, 0, 0, 0, 0], 
   # [0, 0, 0, 0, 0], 
   # [0, 0, 0, 0, 0]]

How to find neighbors of a 2D list in python?, Given a 2D array(m x n). The task is to check if there is any path from top left to bottom right. In the matrix, -1 is considered as blockage (can't go through this cell) � this is what I have so far but it stops at the first iteration of the loops thinking the first element inside the string is B then will return False without ever getting to the 4th element of the first list.

Check for possible path in 2D matrix, Boundary elements are those elements which are not surrounded by elements Please solve it on “PRACTICE ” first, before moving on to the solution. Traverse the matrix and check for every element if that element lies on the boundary or not, If the element lies in the boundary of matrix, then print the element, i.e. if the� Given a 2D list, write a Python program to convert the given list into a flattened list. Method #1: Using chain.iterable()

I'd write the if's, but generating neighbors as in the other answer is elegant.

If you can alter the data structure and need speed then you can use ghost cells.

Surround your grid with zeros like this :

       0 0 0 0
1 2    0 1 2 0
4 5    0 4 5 0
       0 0 0 0

Then you can iterate from 1..n-1 and always have all neighbours

Boundary elements of a Matrix, NumPy specifies the row-axis (students) of a 2D array as “axis-0” and the latest exam score - you need not check how many exams the students have taken. The Python Shapefile Library (pyshp) provides read and write support for the Esri Shapefile format. The Shapefile format is a popular Geographic Information System vector data format created by Esri. To Install pyshp, execute below instruction in your Terminal: pip install pyshp 3. Importing and initializing main Python libraries

One way would be:

def neighbors(m,r,c):
    return sum((
        sum(m[r-1][max(0,c-1):c+2]) if 0 <= r-1 < len(m) else 0,
        sum(m[r  ][max(0,c-1):c+2]) if 0 <= r   < len(m) else 0,
        sum(m[r+1][max(0,c-1):c+2]) if 0 <= r+1 < len(m) else 0,
    )) - m[r][c]

It takes the sum of the 3x3 square around the (r,c) element, then subtracts the value at (r,c).

There are innumerable ways to clean this up based on preference, for example:

def neighbors(m,r,c):
    return sum(
        sum(m[x][max(0,c-1):c+2]) for x in [r-1,r,r+1] if 0 <= x < len(m)
    ) - m[r][c]

The only real somewhat clever thing here is that you can sort of side-step out of bounds errors by using slicing. So x = [1,2,3]; print(x[100:200]) will just print an empty list, no IndexError.

Do I think you should use this code instead of a simple nested for loop? Almost definitely not.

Accessing Data Along Multiple Dimensions in an Array — Python , If you would like to refresh your memory, take a look at the Python tutorial. Understand how to apply some linear algebra operations to n-dimensional arrays without NumPy's main object is the homogeneous multidimensional array. For this reason, it is usually better to use the function linspace that receives as an � The reason is, [0] * m returns just a reference to a list of m zeros, but not a list. The subsequent repeating of this element creates a list of n items that all reference to the same list (just as well as the operation b = a for lists does not create the new list), so all rows in the resulting list are actually the same string.

Quickstart tutorial — NumPy v1.20.dev0 Manual, If you are going to use an integer index to access the list, it is a good idea to use in and not in are Boolean operators that test membership in a sequence. There are two possible ways the Python interpreter could arrange its memory: This process is sometimes called cloning, to avoid the ambiguity of the word copy . List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

11. Lists — How to Think Like a Computer Scientist: Learning with , (The standard library includes additional numeric types, fractions that hold rationals, and Real abstract base class. float also has the following additional methods. Test int objects for membership in constant time instead of iterating through all items. Return a list of the lines in the string, breaking at line boundaries. There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python.

4. Built-in Types — Python 3.3.7 documentation, In this step-by-step tutorial, you'll learn how to use PyGame. the written tutorial to deepen your understanding: Make a 2D Side-Scroller Game With PyGame This program uses a list to create a square window with 500 pixels on each side. Lines 15 to 17 scan and handle events within the game loop. In this tutorial, you'll learn what correlation is and how you can calculate it with Python. You'll use SciPy, NumPy, and Pandas correlation methods to calculate three different correlation coefficients. You'll also see how to visualize data, regression lines, and correlation matrices with Matplotlib.