How to slice a 2D Python Array? Fails with: "TypeError: list indices must be integers, not tuple"

Viewed 39114

I have a 2d array in the numpy module that looks like:

data = array([[1,2,3],
              [4,5,6],
              [7,8,9]])

I want to get a slice of this array that only includes certain columns of element. For example I may want columns 0 and 2:

data = [[1,3],
        [4,6],
        [7,9]]

What is the most Pythonic way to do this? (No for loops please)

I thought this would work:

newArray = data[:,[0,2]]

but it results in a:

TypeError: list indices must be integers, not tuple
8 Answers

The example in question begins with array, not with np.array, and array is not defined as an isolated prefix:

data = array([[1,2,3],
              [4,5,6],
              [7,8,9]])

data[:,[0,2]]

Error:

NameError: name 'array' is not defined

To reproduce the error, you need to drop that array frame (without np. in front, it does not have a definition anyway).

data = [[1,2,3],
        [4,5,6],
        [7,8,9]]

data[:,[0,2]]

Error:

TypeError: list indices must be integers or slices, not tuple

The user has probably used the inner list of the array for tests but asked the question with a copy from a np.array output. At least in 2021, the question is just plain wrong: it cannot be reproduced. And I doubt that the behaviour was different in 2010 (numpy is the basic package of python).

For completeness, as in the other answers:

data = np.array([[1,2,3],
                [4,5,6],
                [7,8,9]])

data[:,[0,2]]

Output:

array([[1, 3],
       [4, 6],
       [7, 9]])

You do not need a nested list to reproduce this. Slicing a one-dimensional list by two dimensions like with

[1,2][:, 0]

throws the same TypeError: list indices must be integers or slices, not tuple.

Related