Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: list indices must be integers or slices, not tuple (when trying to print even columns of matrix)

I’m new here and i have such problem:
I need to print even columns of matrix. When i tried to do this i’ve got such error:

print(array[:, 1::2])
TypeError: list indices must be integers or slices, not tuple

Here is what i tried to solve this problem:

import numpy as np
import random

arr = []
rows = int(input('\nInput the number of rows: '))
cols = int(input('Input the number of cols: '))


def AutoFill(rand_arr, rows, cols):
    for k in range(rows):
        arr = []
        for v in range(cols):
            a = random.randint(-20, 20)
            arr.append(a)
        rand_arr.append(arr)
    rand_arr = np.array([])
    return rand_arr


def PrintArr(array):
    print('Your matrix: ')
    print(np.matrix(array))


def EvenCols(array):
    print(array[:, 1::2])


AutoFill(arr, rows, cols)
PrintArr(arr)
EvenCols(arr)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

arr is a vanilla Python list, not a numpy array. You can’t use tuple indexing on vanilla Python lists.

There are two ways to fix this:

  1. You should transform arr to a numpy array before you pass it into EvenCols(), like so:
EvenCols(np.array(arr))

You can then remove the last two lines of the AutoFill function, since this method modifies the list in-place.

  1. Methods that have side effects can make it harder for others to understand your code. While for this short example it may be fine, a better approach would be to create a new list, in the function, return it, and assign the function’s return value to arr, like so:
def AutoFill(rows, cols):
    rand_arr = []
    for k in range(rows):
        arr = []
        for v in range(cols):
            a = random.randint(-20, 20)
            arr.append(a)
        rand_arr.append(np.array(arr))
    return np.array(rand_arr)

Then, the last three lines would look like:

arr = AutoFill(rows, cols)
PrintArr(arr)
EvenCols(np.array(arr))

Additionally, in this approach, the initial assignment to arr at the top of your code snippet can be removed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading