1

What's wrong with the code below?

arr=numpy.empty((2,2))
arr[0:,0:]=1
print(arr[1:,1:])
arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
print(arr[1:2, 1])

I am getting the following error and not able to slice the array( fifth line). Please help me with this.

TypeError: list indices must be integers, not tuple.

1
  • array[1][1]. I just want to do this by slicing method but not able to to so. Commented Aug 8, 2014 at 21:03

2 Answers 2

1

You rebind the name arr to point to a Python list in your fourth line, and so your question title doesn't quite fit: you're not slicing a 2d numpy array. lists can't be sliced the way that numpy arrays can. Compare:

>>> arr= numpy.array([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])
>>> arr
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> arr[1:2, 1]
array([5])

but

>>> arr.tolist()
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> arr.tolist()[1:2, 1]
Traceback (most recent call last):
  File "<ipython-input-23-4a441cf2eaa9>", line 1, in <module>
    arr.tolist()[1:2, 1]
TypeError: list indices must be integers, not tuple
Sign up to request clarification or add additional context in comments.

Comments

1

arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ]) is a python list,not a numpy array.

You reassign arr with arr=([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ]) to a list.

Make it a numpy array:

In [37]: arr  = numpy.array([ [1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ])

In [38]: arr
Out[38]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [39]: (arr[1:2, 1])
Out[39]: array([5])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.