Is there a difference between `board[x, y]` and `board[x][y]` in Python?Python3 - Count number of occurences of each pair between two listsCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Does Python have a ternary conditional operator?Python join: why is it string.join(list) instead of list.join(string)?Difference between __str__ and __repr__?How do I concatenate two lists in Python?Does Python have a string 'contains' substring method?

Did Michelle Obama have a staff of 23; and Melania have a staff of 4?

Does Medium Armor's Max dex also put a cap on the negative side?

Quick destruction of a helium filled airship?

Weird resistor with dots around it on the schematic

Heyawacky: Ace of Cups

Physical Interpretation of an Overdamped Pendulum

Why does Japan use the same type of AC power outlet as the US?

What's the relationship betweeen MS-DOS and XENIX?

Does the Haste spell's hasted action allow you to make multiple unarmed strikes? Or none at all?

Short comic about alien explorers visiting an abandoned world with giant statues that turn out to be alive but move very slowly

How do ultra-stable oscillators for spacecraft work?

Adding things to bunches of things vs multiplication

Have there ever been other TV shows or Films that told a similiar story to the new 90210 show?

Is nullptr falsy?

Is Fourier series a sampled version of Fourier transform?

What is the fastest way to level past 95 in Diablo II?

Can I use my OWN published papers' images in my thesis without Copyright infringment

When does The Truman Show take place?

Are there any cons in using rounded corners for bar graphs?

Would molten tin solidify and coat an organic horn?

Airline power sockets shut down when I plug my computer in. How can I avoid that?

Select elements of a list by comparing it to another list

What allows us to use imaginary numbers?

Is a USB 3.0 device possible with a four contact USB 2.0 connector?



Is there a difference between `board[x, y]` and `board[x][y]` in Python?


Python3 - Count number of occurences of each pair between two listsCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Does Python have a ternary conditional operator?Python join: why is it string.join(list) instead of list.join(string)?Difference between __str__ and __repr__?How do I concatenate two lists in Python?Does Python have a string 'contains' substring method?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








39















I'm working through a tutorial on GeekforGeeks website and noticed that they are checking a point in an array using board[x,y], which I've never seen before. I don't think this would work, but when I run the program, everything goes as expected.



I tried running a smaller code example using their method outlined above vs the method I'm more familiar with (board[x][y]), but when I run my code, I get TypeError: list indices must be integers or slices, not tuple



My code:



board = [[1,1,1], [1,2,2], [1,2,2]]
win = 'True'

if board[1][1] == 2:
win = 'True by normal standards'
print(win)
if board[1, 1] == 2:
win = 'True by weird standards'
print(win)

print(win)


Their code:



def row_win(board, player): 
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)


Can someone explain to me why board[x,y] works, and what exactly is happening? I've never seen this before except to create lists, and am not grasping it conceptually.










share|improve this question





















  • 1





    If you run in interactive mode (python -i), then type(board) will show you what type board is (numpy.ndarray or pandas.DataFrame). Or look at the lines that create and initialize board.

    – smci
    Aug 5 at 2:03

















39















I'm working through a tutorial on GeekforGeeks website and noticed that they are checking a point in an array using board[x,y], which I've never seen before. I don't think this would work, but when I run the program, everything goes as expected.



I tried running a smaller code example using their method outlined above vs the method I'm more familiar with (board[x][y]), but when I run my code, I get TypeError: list indices must be integers or slices, not tuple



My code:



board = [[1,1,1], [1,2,2], [1,2,2]]
win = 'True'

if board[1][1] == 2:
win = 'True by normal standards'
print(win)
if board[1, 1] == 2:
win = 'True by weird standards'
print(win)

print(win)


Their code:



def row_win(board, player): 
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)


Can someone explain to me why board[x,y] works, and what exactly is happening? I've never seen this before except to create lists, and am not grasping it conceptually.










share|improve this question





















  • 1





    If you run in interactive mode (python -i), then type(board) will show you what type board is (numpy.ndarray or pandas.DataFrame). Or look at the lines that create and initialize board.

    – smci
    Aug 5 at 2:03













39












39








39


1






I'm working through a tutorial on GeekforGeeks website and noticed that they are checking a point in an array using board[x,y], which I've never seen before. I don't think this would work, but when I run the program, everything goes as expected.



I tried running a smaller code example using their method outlined above vs the method I'm more familiar with (board[x][y]), but when I run my code, I get TypeError: list indices must be integers or slices, not tuple



My code:



board = [[1,1,1], [1,2,2], [1,2,2]]
win = 'True'

if board[1][1] == 2:
win = 'True by normal standards'
print(win)
if board[1, 1] == 2:
win = 'True by weird standards'
print(win)

print(win)


Their code:



def row_win(board, player): 
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)


Can someone explain to me why board[x,y] works, and what exactly is happening? I've never seen this before except to create lists, and am not grasping it conceptually.










share|improve this question
















I'm working through a tutorial on GeekforGeeks website and noticed that they are checking a point in an array using board[x,y], which I've never seen before. I don't think this would work, but when I run the program, everything goes as expected.



I tried running a smaller code example using their method outlined above vs the method I'm more familiar with (board[x][y]), but when I run my code, I get TypeError: list indices must be integers or slices, not tuple



My code:



board = [[1,1,1], [1,2,2], [1,2,2]]
win = 'True'

if board[1][1] == 2:
win = 'True by normal standards'
print(win)
if board[1, 1] == 2:
win = 'True by weird standards'
print(win)

print(win)


Their code:



def row_win(board, player): 
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)


Can someone explain to me why board[x,y] works, and what exactly is happening? I've never seen this before except to create lists, and am not grasping it conceptually.







python arrays list numpy indexing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 6 at 0:56









U10-Forward

27.9k5 gold badges21 silver badges48 bronze badges




27.9k5 gold badges21 silver badges48 bronze badges










asked Aug 5 at 1:41









Broski-ACBroski-AC

2092 silver badges5 bronze badges




2092 silver badges5 bronze badges










  • 1





    If you run in interactive mode (python -i), then type(board) will show you what type board is (numpy.ndarray or pandas.DataFrame). Or look at the lines that create and initialize board.

    – smci
    Aug 5 at 2:03












  • 1





    If you run in interactive mode (python -i), then type(board) will show you what type board is (numpy.ndarray or pandas.DataFrame). Or look at the lines that create and initialize board.

    – smci
    Aug 5 at 2:03







1




1





If you run in interactive mode (python -i), then type(board) will show you what type board is (numpy.ndarray or pandas.DataFrame). Or look at the lines that create and initialize board.

– smci
Aug 5 at 2:03





If you run in interactive mode (python -i), then type(board) will show you what type board is (numpy.ndarray or pandas.DataFrame). Or look at the lines that create and initialize board.

– smci
Aug 5 at 2:03












5 Answers
5






active

oldest

votes


















35














They're able to do that since they're using NumPy, which won't throw an error on that.



>>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
>>> a[1,1]
2
>>> # equivalent to
>>> a = [[1,1,1], [1,2,2], [1,2,2]]
>>> a[1][1]
2
>>>





share|improve this answer



























  • And is it the same in numpy? Or is one of the two (significantly) more performant or in any other way preferable?

    – lucidbrot
    Aug 5 at 10:04







  • 12





    @lucidbrot: a[1,1] would be more performant in numpy, as it avoids creating additional numpy array wrappers; a[1][1] has to load a, index to 1, creating a wrapper for that row, then index to 1 on that row to get the cell's value, then clean up the wrapper. a[1,1] directly loads the cell's value without creating additional wrapper objects (it does have to make a tuple on demand if the indices aren't constant, but small tuple literals are specially optimized in Python, so the cost is pretty small).

    – ShadowRanger
    Aug 5 at 14:24



















6














That works because the object they are using (in this case numpy array) overloads the __getitem__ method. See this toy example:



class MyArray:
def __init__(self, arr):
self.arr = arr
def __getitem__(self, t):
return self.arr[t[0]][t[1]]

myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]])
print(myarr[0,1])





share|improve this answer
































    4














    It does not actually work in base Python (like your example). If you run your code, Python throws an exception: 'TypeError: list indices must be integers or slices, not tuple'.



    The 1, 1 passed to board is interpreted as a tuple and since board should be indexed with integers or slices, this won't work.



    However, if board were some type of array-like data structure and the developer had implemented support for indexing with tuples, this would work. An example of this is arrays in numpy.






    share|improve this answer






















    • 3





      Don't say "It does not actually work." You mean "It does not actually work in base Python, if board is a list-of-lists.

      – smci
      Aug 5 at 2:04






    • 1





      I felt that was implied, given the example under discussion, but I've updated the answer.

      – Grismar
      Aug 5 at 2:06






    • 1





      Grismar the OP is clearly unaware of numpy/pandas, and not in the habit of doing type(board) to actually see what type of object it is. You might think that's all implied for advanced users, but it sure ain't for new users.

      – smci
      Aug 5 at 2:08







    • 2





      Even the updated answer falsely implies that this won’t work without third-party libraries, whereas it clearly does: Code as trivial as x = ; x[1, 1] = 42 works as expected. Or, more to the point, nothing forbids somebody to implement a 2D array class in base Python with very little code.

      – Konrad Rudolph
      Aug 5 at 15:35












    • @Konrad Rudolph - the example you're giving is a dictionary that would be indexed with a tuple. That's not just a horrible anti-pattern, but also clearly not what the OP is asking about. I agreed to a point with what smci was saying - it may have been unclear that I meant base python; many libraries actually implement arrays with multi-dimensional indices. However, the example you provide shows that doing so is not at all trivial and certainly not base Python. Finally, if a required solution would be best realised with a dict indexed with tuples, that's perfectly in line with my answer.

      – Grismar
      Aug 5 at 23:48


















    3














    The board[x, y] syntax is probably being applied onto a numpy array, which accepts this syntax in order to implement row/column indexed slicing operations. Take a look at these examples:



    >>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # creates 2D array
    >>> x
    array([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

    >>> x[1] # get second row (remember, index starts at 0)
    array([4, 5, 6])

    >>> x[:, 2] # get third column
    array([3, 6, 9])

    >>> x[1, 2] # get element on second row, third column
    6

    >>> x[1][2] # same as before but with non-broadcasting syntax (i.e. works for lists as you are used to)
    6

    >>> x[1, 0:2] # get first two elements of second row
    array([4, 5])

    >>> x[0:2, 0:2] # subsets the original array, "extracting" values from the first two columns/rows only
    array([[1, 2],
    [4, 5]])


    Of course, writing my_list[x, y] throws an error because x, y is actually a tuple (x, y), and regular lists can't work with tuples as an indexing value.






    share|improve this answer



























    • Thank you! I'm new to NumPy, so this is extremely useful

      – Broski-AC
      Aug 5 at 2:00


















    2














    Because their board is either numpy.ndarray or some type that wraps it, e.g. pandas.DataFrame



    You should have done type(board). Or show us the lines that create and initialize board.



    Also, when you say "when I run the program, everything goes as expected", you should run in interactive mode (python -i), then you could run queries like type(board)






    share|improve this answer



























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57351363%2fis-there-a-difference-between-boardx-y-and-boardxy-in-python%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      35














      They're able to do that since they're using NumPy, which won't throw an error on that.



      >>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
      >>> a[1,1]
      2
      >>> # equivalent to
      >>> a = [[1,1,1], [1,2,2], [1,2,2]]
      >>> a[1][1]
      2
      >>>





      share|improve this answer



























      • And is it the same in numpy? Or is one of the two (significantly) more performant or in any other way preferable?

        – lucidbrot
        Aug 5 at 10:04







      • 12





        @lucidbrot: a[1,1] would be more performant in numpy, as it avoids creating additional numpy array wrappers; a[1][1] has to load a, index to 1, creating a wrapper for that row, then index to 1 on that row to get the cell's value, then clean up the wrapper. a[1,1] directly loads the cell's value without creating additional wrapper objects (it does have to make a tuple on demand if the indices aren't constant, but small tuple literals are specially optimized in Python, so the cost is pretty small).

        – ShadowRanger
        Aug 5 at 14:24
















      35














      They're able to do that since they're using NumPy, which won't throw an error on that.



      >>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
      >>> a[1,1]
      2
      >>> # equivalent to
      >>> a = [[1,1,1], [1,2,2], [1,2,2]]
      >>> a[1][1]
      2
      >>>





      share|improve this answer



























      • And is it the same in numpy? Or is one of the two (significantly) more performant or in any other way preferable?

        – lucidbrot
        Aug 5 at 10:04







      • 12





        @lucidbrot: a[1,1] would be more performant in numpy, as it avoids creating additional numpy array wrappers; a[1][1] has to load a, index to 1, creating a wrapper for that row, then index to 1 on that row to get the cell's value, then clean up the wrapper. a[1,1] directly loads the cell's value without creating additional wrapper objects (it does have to make a tuple on demand if the indices aren't constant, but small tuple literals are specially optimized in Python, so the cost is pretty small).

        – ShadowRanger
        Aug 5 at 14:24














      35












      35








      35







      They're able to do that since they're using NumPy, which won't throw an error on that.



      >>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
      >>> a[1,1]
      2
      >>> # equivalent to
      >>> a = [[1,1,1], [1,2,2], [1,2,2]]
      >>> a[1][1]
      2
      >>>





      share|improve this answer















      They're able to do that since they're using NumPy, which won't throw an error on that.



      >>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
      >>> a[1,1]
      2
      >>> # equivalent to
      >>> a = [[1,1,1], [1,2,2], [1,2,2]]
      >>> a[1][1]
      2
      >>>






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 5 at 1:46

























      answered Aug 5 at 1:44









      U10-ForwardU10-Forward

      27.9k5 gold badges21 silver badges48 bronze badges




      27.9k5 gold badges21 silver badges48 bronze badges















      • And is it the same in numpy? Or is one of the two (significantly) more performant or in any other way preferable?

        – lucidbrot
        Aug 5 at 10:04







      • 12





        @lucidbrot: a[1,1] would be more performant in numpy, as it avoids creating additional numpy array wrappers; a[1][1] has to load a, index to 1, creating a wrapper for that row, then index to 1 on that row to get the cell's value, then clean up the wrapper. a[1,1] directly loads the cell's value without creating additional wrapper objects (it does have to make a tuple on demand if the indices aren't constant, but small tuple literals are specially optimized in Python, so the cost is pretty small).

        – ShadowRanger
        Aug 5 at 14:24


















      • And is it the same in numpy? Or is one of the two (significantly) more performant or in any other way preferable?

        – lucidbrot
        Aug 5 at 10:04







      • 12





        @lucidbrot: a[1,1] would be more performant in numpy, as it avoids creating additional numpy array wrappers; a[1][1] has to load a, index to 1, creating a wrapper for that row, then index to 1 on that row to get the cell's value, then clean up the wrapper. a[1,1] directly loads the cell's value without creating additional wrapper objects (it does have to make a tuple on demand if the indices aren't constant, but small tuple literals are specially optimized in Python, so the cost is pretty small).

        – ShadowRanger
        Aug 5 at 14:24

















      And is it the same in numpy? Or is one of the two (significantly) more performant or in any other way preferable?

      – lucidbrot
      Aug 5 at 10:04






      And is it the same in numpy? Or is one of the two (significantly) more performant or in any other way preferable?

      – lucidbrot
      Aug 5 at 10:04





      12




      12





      @lucidbrot: a[1,1] would be more performant in numpy, as it avoids creating additional numpy array wrappers; a[1][1] has to load a, index to 1, creating a wrapper for that row, then index to 1 on that row to get the cell's value, then clean up the wrapper. a[1,1] directly loads the cell's value without creating additional wrapper objects (it does have to make a tuple on demand if the indices aren't constant, but small tuple literals are specially optimized in Python, so the cost is pretty small).

      – ShadowRanger
      Aug 5 at 14:24






      @lucidbrot: a[1,1] would be more performant in numpy, as it avoids creating additional numpy array wrappers; a[1][1] has to load a, index to 1, creating a wrapper for that row, then index to 1 on that row to get the cell's value, then clean up the wrapper. a[1,1] directly loads the cell's value without creating additional wrapper objects (it does have to make a tuple on demand if the indices aren't constant, but small tuple literals are specially optimized in Python, so the cost is pretty small).

      – ShadowRanger
      Aug 5 at 14:24














      6














      That works because the object they are using (in this case numpy array) overloads the __getitem__ method. See this toy example:



      class MyArray:
      def __init__(self, arr):
      self.arr = arr
      def __getitem__(self, t):
      return self.arr[t[0]][t[1]]

      myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]])
      print(myarr[0,1])





      share|improve this answer





























        6














        That works because the object they are using (in this case numpy array) overloads the __getitem__ method. See this toy example:



        class MyArray:
        def __init__(self, arr):
        self.arr = arr
        def __getitem__(self, t):
        return self.arr[t[0]][t[1]]

        myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]])
        print(myarr[0,1])





        share|improve this answer



























          6












          6








          6







          That works because the object they are using (in this case numpy array) overloads the __getitem__ method. See this toy example:



          class MyArray:
          def __init__(self, arr):
          self.arr = arr
          def __getitem__(self, t):
          return self.arr[t[0]][t[1]]

          myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]])
          print(myarr[0,1])





          share|improve this answer













          That works because the object they are using (in this case numpy array) overloads the __getitem__ method. See this toy example:



          class MyArray:
          def __init__(self, arr):
          self.arr = arr
          def __getitem__(self, t):
          return self.arr[t[0]][t[1]]

          myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]])
          print(myarr[0,1])






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 5 at 13:37









          AntAnt

          3,7471 gold badge19 silver badges38 bronze badges




          3,7471 gold badge19 silver badges38 bronze badges
























              4














              It does not actually work in base Python (like your example). If you run your code, Python throws an exception: 'TypeError: list indices must be integers or slices, not tuple'.



              The 1, 1 passed to board is interpreted as a tuple and since board should be indexed with integers or slices, this won't work.



              However, if board were some type of array-like data structure and the developer had implemented support for indexing with tuples, this would work. An example of this is arrays in numpy.






              share|improve this answer






















              • 3





                Don't say "It does not actually work." You mean "It does not actually work in base Python, if board is a list-of-lists.

                – smci
                Aug 5 at 2:04






              • 1





                I felt that was implied, given the example under discussion, but I've updated the answer.

                – Grismar
                Aug 5 at 2:06






              • 1





                Grismar the OP is clearly unaware of numpy/pandas, and not in the habit of doing type(board) to actually see what type of object it is. You might think that's all implied for advanced users, but it sure ain't for new users.

                – smci
                Aug 5 at 2:08







              • 2





                Even the updated answer falsely implies that this won’t work without third-party libraries, whereas it clearly does: Code as trivial as x = ; x[1, 1] = 42 works as expected. Or, more to the point, nothing forbids somebody to implement a 2D array class in base Python with very little code.

                – Konrad Rudolph
                Aug 5 at 15:35












              • @Konrad Rudolph - the example you're giving is a dictionary that would be indexed with a tuple. That's not just a horrible anti-pattern, but also clearly not what the OP is asking about. I agreed to a point with what smci was saying - it may have been unclear that I meant base python; many libraries actually implement arrays with multi-dimensional indices. However, the example you provide shows that doing so is not at all trivial and certainly not base Python. Finally, if a required solution would be best realised with a dict indexed with tuples, that's perfectly in line with my answer.

                – Grismar
                Aug 5 at 23:48















              4














              It does not actually work in base Python (like your example). If you run your code, Python throws an exception: 'TypeError: list indices must be integers or slices, not tuple'.



              The 1, 1 passed to board is interpreted as a tuple and since board should be indexed with integers or slices, this won't work.



              However, if board were some type of array-like data structure and the developer had implemented support for indexing with tuples, this would work. An example of this is arrays in numpy.






              share|improve this answer






















              • 3





                Don't say "It does not actually work." You mean "It does not actually work in base Python, if board is a list-of-lists.

                – smci
                Aug 5 at 2:04






              • 1





                I felt that was implied, given the example under discussion, but I've updated the answer.

                – Grismar
                Aug 5 at 2:06






              • 1





                Grismar the OP is clearly unaware of numpy/pandas, and not in the habit of doing type(board) to actually see what type of object it is. You might think that's all implied for advanced users, but it sure ain't for new users.

                – smci
                Aug 5 at 2:08







              • 2





                Even the updated answer falsely implies that this won’t work without third-party libraries, whereas it clearly does: Code as trivial as x = ; x[1, 1] = 42 works as expected. Or, more to the point, nothing forbids somebody to implement a 2D array class in base Python with very little code.

                – Konrad Rudolph
                Aug 5 at 15:35












              • @Konrad Rudolph - the example you're giving is a dictionary that would be indexed with a tuple. That's not just a horrible anti-pattern, but also clearly not what the OP is asking about. I agreed to a point with what smci was saying - it may have been unclear that I meant base python; many libraries actually implement arrays with multi-dimensional indices. However, the example you provide shows that doing so is not at all trivial and certainly not base Python. Finally, if a required solution would be best realised with a dict indexed with tuples, that's perfectly in line with my answer.

                – Grismar
                Aug 5 at 23:48













              4












              4








              4







              It does not actually work in base Python (like your example). If you run your code, Python throws an exception: 'TypeError: list indices must be integers or slices, not tuple'.



              The 1, 1 passed to board is interpreted as a tuple and since board should be indexed with integers or slices, this won't work.



              However, if board were some type of array-like data structure and the developer had implemented support for indexing with tuples, this would work. An example of this is arrays in numpy.






              share|improve this answer















              It does not actually work in base Python (like your example). If you run your code, Python throws an exception: 'TypeError: list indices must be integers or slices, not tuple'.



              The 1, 1 passed to board is interpreted as a tuple and since board should be indexed with integers or slices, this won't work.



              However, if board were some type of array-like data structure and the developer had implemented support for indexing with tuples, this would work. An example of this is arrays in numpy.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 5 at 2:05

























              answered Aug 5 at 1:45









              GrismarGrismar

              2,7431 gold badge9 silver badges24 bronze badges




              2,7431 gold badge9 silver badges24 bronze badges










              • 3





                Don't say "It does not actually work." You mean "It does not actually work in base Python, if board is a list-of-lists.

                – smci
                Aug 5 at 2:04






              • 1





                I felt that was implied, given the example under discussion, but I've updated the answer.

                – Grismar
                Aug 5 at 2:06






              • 1





                Grismar the OP is clearly unaware of numpy/pandas, and not in the habit of doing type(board) to actually see what type of object it is. You might think that's all implied for advanced users, but it sure ain't for new users.

                – smci
                Aug 5 at 2:08







              • 2





                Even the updated answer falsely implies that this won’t work without third-party libraries, whereas it clearly does: Code as trivial as x = ; x[1, 1] = 42 works as expected. Or, more to the point, nothing forbids somebody to implement a 2D array class in base Python with very little code.

                – Konrad Rudolph
                Aug 5 at 15:35












              • @Konrad Rudolph - the example you're giving is a dictionary that would be indexed with a tuple. That's not just a horrible anti-pattern, but also clearly not what the OP is asking about. I agreed to a point with what smci was saying - it may have been unclear that I meant base python; many libraries actually implement arrays with multi-dimensional indices. However, the example you provide shows that doing so is not at all trivial and certainly not base Python. Finally, if a required solution would be best realised with a dict indexed with tuples, that's perfectly in line with my answer.

                – Grismar
                Aug 5 at 23:48












              • 3





                Don't say "It does not actually work." You mean "It does not actually work in base Python, if board is a list-of-lists.

                – smci
                Aug 5 at 2:04






              • 1





                I felt that was implied, given the example under discussion, but I've updated the answer.

                – Grismar
                Aug 5 at 2:06






              • 1





                Grismar the OP is clearly unaware of numpy/pandas, and not in the habit of doing type(board) to actually see what type of object it is. You might think that's all implied for advanced users, but it sure ain't for new users.

                – smci
                Aug 5 at 2:08







              • 2





                Even the updated answer falsely implies that this won’t work without third-party libraries, whereas it clearly does: Code as trivial as x = ; x[1, 1] = 42 works as expected. Or, more to the point, nothing forbids somebody to implement a 2D array class in base Python with very little code.

                – Konrad Rudolph
                Aug 5 at 15:35












              • @Konrad Rudolph - the example you're giving is a dictionary that would be indexed with a tuple. That's not just a horrible anti-pattern, but also clearly not what the OP is asking about. I agreed to a point with what smci was saying - it may have been unclear that I meant base python; many libraries actually implement arrays with multi-dimensional indices. However, the example you provide shows that doing so is not at all trivial and certainly not base Python. Finally, if a required solution would be best realised with a dict indexed with tuples, that's perfectly in line with my answer.

                – Grismar
                Aug 5 at 23:48







              3




              3





              Don't say "It does not actually work." You mean "It does not actually work in base Python, if board is a list-of-lists.

              – smci
              Aug 5 at 2:04





              Don't say "It does not actually work." You mean "It does not actually work in base Python, if board is a list-of-lists.

              – smci
              Aug 5 at 2:04




              1




              1





              I felt that was implied, given the example under discussion, but I've updated the answer.

              – Grismar
              Aug 5 at 2:06





              I felt that was implied, given the example under discussion, but I've updated the answer.

              – Grismar
              Aug 5 at 2:06




              1




              1





              Grismar the OP is clearly unaware of numpy/pandas, and not in the habit of doing type(board) to actually see what type of object it is. You might think that's all implied for advanced users, but it sure ain't for new users.

              – smci
              Aug 5 at 2:08






              Grismar the OP is clearly unaware of numpy/pandas, and not in the habit of doing type(board) to actually see what type of object it is. You might think that's all implied for advanced users, but it sure ain't for new users.

              – smci
              Aug 5 at 2:08





              2




              2





              Even the updated answer falsely implies that this won’t work without third-party libraries, whereas it clearly does: Code as trivial as x = ; x[1, 1] = 42 works as expected. Or, more to the point, nothing forbids somebody to implement a 2D array class in base Python with very little code.

              – Konrad Rudolph
              Aug 5 at 15:35






              Even the updated answer falsely implies that this won’t work without third-party libraries, whereas it clearly does: Code as trivial as x = ; x[1, 1] = 42 works as expected. Or, more to the point, nothing forbids somebody to implement a 2D array class in base Python with very little code.

              – Konrad Rudolph
              Aug 5 at 15:35














              @Konrad Rudolph - the example you're giving is a dictionary that would be indexed with a tuple. That's not just a horrible anti-pattern, but also clearly not what the OP is asking about. I agreed to a point with what smci was saying - it may have been unclear that I meant base python; many libraries actually implement arrays with multi-dimensional indices. However, the example you provide shows that doing so is not at all trivial and certainly not base Python. Finally, if a required solution would be best realised with a dict indexed with tuples, that's perfectly in line with my answer.

              – Grismar
              Aug 5 at 23:48





              @Konrad Rudolph - the example you're giving is a dictionary that would be indexed with a tuple. That's not just a horrible anti-pattern, but also clearly not what the OP is asking about. I agreed to a point with what smci was saying - it may have been unclear that I meant base python; many libraries actually implement arrays with multi-dimensional indices. However, the example you provide shows that doing so is not at all trivial and certainly not base Python. Finally, if a required solution would be best realised with a dict indexed with tuples, that's perfectly in line with my answer.

              – Grismar
              Aug 5 at 23:48











              3














              The board[x, y] syntax is probably being applied onto a numpy array, which accepts this syntax in order to implement row/column indexed slicing operations. Take a look at these examples:



              >>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # creates 2D array
              >>> x
              array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

              >>> x[1] # get second row (remember, index starts at 0)
              array([4, 5, 6])

              >>> x[:, 2] # get third column
              array([3, 6, 9])

              >>> x[1, 2] # get element on second row, third column
              6

              >>> x[1][2] # same as before but with non-broadcasting syntax (i.e. works for lists as you are used to)
              6

              >>> x[1, 0:2] # get first two elements of second row
              array([4, 5])

              >>> x[0:2, 0:2] # subsets the original array, "extracting" values from the first two columns/rows only
              array([[1, 2],
              [4, 5]])


              Of course, writing my_list[x, y] throws an error because x, y is actually a tuple (x, y), and regular lists can't work with tuples as an indexing value.






              share|improve this answer



























              • Thank you! I'm new to NumPy, so this is extremely useful

                – Broski-AC
                Aug 5 at 2:00















              3














              The board[x, y] syntax is probably being applied onto a numpy array, which accepts this syntax in order to implement row/column indexed slicing operations. Take a look at these examples:



              >>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # creates 2D array
              >>> x
              array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

              >>> x[1] # get second row (remember, index starts at 0)
              array([4, 5, 6])

              >>> x[:, 2] # get third column
              array([3, 6, 9])

              >>> x[1, 2] # get element on second row, third column
              6

              >>> x[1][2] # same as before but with non-broadcasting syntax (i.e. works for lists as you are used to)
              6

              >>> x[1, 0:2] # get first two elements of second row
              array([4, 5])

              >>> x[0:2, 0:2] # subsets the original array, "extracting" values from the first two columns/rows only
              array([[1, 2],
              [4, 5]])


              Of course, writing my_list[x, y] throws an error because x, y is actually a tuple (x, y), and regular lists can't work with tuples as an indexing value.






              share|improve this answer



























              • Thank you! I'm new to NumPy, so this is extremely useful

                – Broski-AC
                Aug 5 at 2:00













              3












              3








              3







              The board[x, y] syntax is probably being applied onto a numpy array, which accepts this syntax in order to implement row/column indexed slicing operations. Take a look at these examples:



              >>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # creates 2D array
              >>> x
              array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

              >>> x[1] # get second row (remember, index starts at 0)
              array([4, 5, 6])

              >>> x[:, 2] # get third column
              array([3, 6, 9])

              >>> x[1, 2] # get element on second row, third column
              6

              >>> x[1][2] # same as before but with non-broadcasting syntax (i.e. works for lists as you are used to)
              6

              >>> x[1, 0:2] # get first two elements of second row
              array([4, 5])

              >>> x[0:2, 0:2] # subsets the original array, "extracting" values from the first two columns/rows only
              array([[1, 2],
              [4, 5]])


              Of course, writing my_list[x, y] throws an error because x, y is actually a tuple (x, y), and regular lists can't work with tuples as an indexing value.






              share|improve this answer















              The board[x, y] syntax is probably being applied onto a numpy array, which accepts this syntax in order to implement row/column indexed slicing operations. Take a look at these examples:



              >>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # creates 2D array
              >>> x
              array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

              >>> x[1] # get second row (remember, index starts at 0)
              array([4, 5, 6])

              >>> x[:, 2] # get third column
              array([3, 6, 9])

              >>> x[1, 2] # get element on second row, third column
              6

              >>> x[1][2] # same as before but with non-broadcasting syntax (i.e. works for lists as you are used to)
              6

              >>> x[1, 0:2] # get first two elements of second row
              array([4, 5])

              >>> x[0:2, 0:2] # subsets the original array, "extracting" values from the first two columns/rows only
              array([[1, 2],
              [4, 5]])


              Of course, writing my_list[x, y] throws an error because x, y is actually a tuple (x, y), and regular lists can't work with tuples as an indexing value.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 5 at 2:00

























              answered Aug 5 at 1:58









              jfaccionijfaccioni

              1,1321 gold badge2 silver badges12 bronze badges




              1,1321 gold badge2 silver badges12 bronze badges















              • Thank you! I'm new to NumPy, so this is extremely useful

                – Broski-AC
                Aug 5 at 2:00

















              • Thank you! I'm new to NumPy, so this is extremely useful

                – Broski-AC
                Aug 5 at 2:00
















              Thank you! I'm new to NumPy, so this is extremely useful

              – Broski-AC
              Aug 5 at 2:00





              Thank you! I'm new to NumPy, so this is extremely useful

              – Broski-AC
              Aug 5 at 2:00











              2














              Because their board is either numpy.ndarray or some type that wraps it, e.g. pandas.DataFrame



              You should have done type(board). Or show us the lines that create and initialize board.



              Also, when you say "when I run the program, everything goes as expected", you should run in interactive mode (python -i), then you could run queries like type(board)






              share|improve this answer





























                2














                Because their board is either numpy.ndarray or some type that wraps it, e.g. pandas.DataFrame



                You should have done type(board). Or show us the lines that create and initialize board.



                Also, when you say "when I run the program, everything goes as expected", you should run in interactive mode (python -i), then you could run queries like type(board)






                share|improve this answer



























                  2












                  2








                  2







                  Because their board is either numpy.ndarray or some type that wraps it, e.g. pandas.DataFrame



                  You should have done type(board). Or show us the lines that create and initialize board.



                  Also, when you say "when I run the program, everything goes as expected", you should run in interactive mode (python -i), then you could run queries like type(board)






                  share|improve this answer













                  Because their board is either numpy.ndarray or some type that wraps it, e.g. pandas.DataFrame



                  You should have done type(board). Or show us the lines that create and initialize board.



                  Also, when you say "when I run the program, everything goes as expected", you should run in interactive mode (python -i), then you could run queries like type(board)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Aug 5 at 2:01









                  smcismci

                  16.8k6 gold badges82 silver badges111 bronze badges




                  16.8k6 gold badges82 silver badges111 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57351363%2fis-there-a-difference-between-boardx-y-and-boardxy-in-python%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

                      Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?