3

How do you use numpy.mgrid with a variable number of indices? I can't find any examples on github of anyone using this with anything but hardcoded values.

import numpy as np
np.mgrid[1:10, 1:10] # this works fine

x = (1, 10)
np.mgrid[x[0]:x[1], x[0]:x[1]] # hardcoded

xs = [(1,10)] * 10
np.mgrid[*xs????] # I can't get anything to work here

1 Answer 1

4

This seems to work:

np.mgrid[[slice(i,j) for i,j in [(1,10)]*10]]

though with *10 it is too large

It's derived from that fact

np.mgrid[slice(1,10),slice(1,10)]  # same as
np.mgrid[1:10,1:10]
Sign up to request clarification or add additional context in comments.

3 Comments

Would it be correct to say that the notation in your last line is just "syntactic sugar" to create the slice objects?
Great, thanks! Never had the occasion to use slice() before, nice.
Yes, the Python interpreter converts the [x:y:z] to a slice object. docs.python.org/2/reference/…

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.