HotWheels
HotWheels

Reputation: 444

Python 2D Array list indices must be integers or slices, not tuple

I am trying to learn Python 2D arrays and I am trying to add to an empty one but am getting the error list indices must be integers or slices, not tuple

I wrote what I wanted to do in Java and am trying to translate it over to Python

My Java code:

Object[][] memoryArray = new Object[256][17];

        int memoryRow, memoryCol;
        int MBR = 12;
        int addr = MBR;
        memoryRow = addr / 16;
        memoryCol = addr % 16 + 1;
        memoryArray[memoryRow][memoryCol] = " "+Integer.toString(MBR);
        for (Object element: memoryArray) {
            System.out.println(element);
     }

My Python Code:

memArray = [[None], [None]]
MBR = 55
address = MBR 
memR = (address / 16)
memC = (address % 16 + 1)
memArray[[memR], [memC]] = " " + str(MBR)

If anyone could lead me to any pointers on how I should correctly implement this logic in Python? I am not sure what the error is trying to indicate.

I also was wondering if I would be better off using Numpy Arrays?

Upvotes: 1

Views: 189

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150815

Java newbies here as well, but let's try translate together:

memArray = [[None], [None]]

is not a Python equivalence for

Object[][] memoryArray = new Object[256][17];

Instead:

memArray = [[None for _ in range(17)] for _ in range(256)]

And

# Java
memoryArray[memoryRow][memoryCol] = " "+Integer.toString(MBR);

translate directly to:

memArray[memR][memC] = " " + str(MBR)

And lastly, while Numpy array might help with advanced indexing over Python's list, if you are working with strings/objects, you wouldn't see much improvement in computing efficiency.

Upvotes: 2

Flavio Moraes
Flavio Moraes

Reputation: 1351

I think what you want is memArray[memR][memC] = " " + str(MBR) but the way it is it will not work because 1) you have to ensure memR is integer and 2) because your list is empty

Upvotes: 0

Related Questions