4

Let's say I have 2D list and I want to do a check if previous/next element equals something. What is the best way to make sure that I will not access list[-1][-1] or list[len + 1][len + 1]?

Here's an example of what I'm trying to do:

if list[y + 1][x] == value and list[y - 1][x] == value:
    do something
elif list[y][x + 1] == value and list[y][x - 1] == value:
    do something else
... # end so on

I can't see any other options except for doing:

if y - 1 > 0 and y + 1 < len(list) and x - 1 > 0 and x + 1 < len(list[y]):

Which doesn't seem right...

sloth
  • 99,095
  • 21
  • 171
  • 219
Ruslan Osipov
  • 5,655
  • 4
  • 29
  • 44
  • Well, you're "other option" would look better if you wrote it like this: `if 0 < y < len(list) - 1 and 0 < x < len(list[0]) - 1:` – Joel Cornett Aug 05 '12 at 02:56
  • @pyrate no offense, but something seems off about having to iterate through the indices of a list (2D or not) in Python. I get the sense there's an overall better way that we just can't know without knowing the problem better. – kojiro Aug 05 '12 at 02:58
  • @kojiro - I agree that this doesn't look like a good solution, something just smells wrong here. – James Black Aug 05 '12 at 03:00
  • @kojiro: I disagree. It looks like he's working with a coordinate system (it's tagged pygame- it could be, for example, a character moving around a room, or pieces moving on a board). – David Robinson Aug 05 '12 at 03:00
  • @DavidRobinson Either we'll know, or we'll never know. :) – kojiro Aug 05 '12 at 03:01
  • @kojiro I agree that it's maybe not a best way to check for neighbors. I am trying to output tile depending on surrounding neighbors. – Ruslan Osipov Aug 05 '12 at 03:03
  • @kojiro: Would you agree that when one is working with an XY coordinate system, it's reasonable to use indices? (Now that pyrate's mentioned tiles it seems clear!) – David Robinson Aug 05 '12 at 03:03
  • @pyrate [You mean like this?](http://stackoverflow.com/questions/1620940/determining-neighbours-of-cell-two-dimensional-list) – kojiro Aug 05 '12 at 03:05
  • @DavidRobinson and you are absolutely right, it's a game, every tile has a bunch of variations like {'ns': (0, 1)} - "tile connected with same tiles from north and south will use image with coordinates 0, 1" – Ruslan Osipov Aug 05 '12 at 03:06

1 Answers1

5

A common way to solve this is to add some "padding" around your grid that contains a sentinel value that indicates you are off the grid (such as 0 or -1 or None or something). Your valid indexes, instead of being from 0 to size-1, would be from 1 to size (with a list length of size+2).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285