user1299784 - 6 months ago 69

Python Question

Given an n by n matrix (technically an np.array) L, I wish to remove the kth row and kth column. This line of code works as expected (it selects the 1st through 3rd rows and columns):

`Lt = L[(1,2,3),(1,2,3)]`

When I try to replace (1,2,3) by a dynamically generated tuple excluding the k, it fails:

`keep = (i for i in range(n) if i != k)`

Lt = L[keep,keep]

# IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

How can I do this properly?

Answer

`keep = (i for i in range(n) if i != k)`

This is a generator expression, not a generated tuple itself; instead, try

```
keep = tuple(i for i in range(n) if i != k)
```