Vivek Subramanian
Vivek Subramanian

Reputation: 1234

Shape of list with numpy arrays

I created a list of N numpy arrays in Python, each of which is size D by P. When I call numpy.shape(my_list), I get back the tuple (N, D, P). When the arrays that I append to my list are not the same size (or if I append items that are not arrays), numpy.shape throws an error.

  1. If I want the shape of each array in the list, do I have to resort to list comprehension or is there a faster way to do this?
  2. Does numpy simply iterate through the list, checking to make sure that each element is an array of the same size as the previous one, and decide based on that whether to return a tuple or throw an error?

Upvotes: 2

Views: 9035

Answers (1)

user2357112
user2357112

Reputation: 280227

If I want the shape of each array in the list, do I have to resort to list comprehension or is there a faster way to do this?

List comprehension.

Does numpy simply iterate through the list, checking to make sure that each element is an array of the same size as the previous one, and decide based on that whether to return a tuple or throw an error?

NumPy calls asarray on the list, building an entire array just to get the shape. (This is not something that anyone has bothered to optimize.)

Upvotes: 1

Related Questions