memoryview (was "len() on mutables vs. immutables")

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Feb 8 15:50:32 CET 2013


On 8 February 2013 06:24, Demian Brecht <demianbrecht at gmail.com> wrote:
> On 2013-02-07 8:30 PM, "Terry Reedy" <tjreedy at udel.edu> wrote:
>
> If a memoryview (3+) is representing a non-continuguous block of memory (>
> 1
> ndim), will len(obj) not return incorrect results? It seems to be
> reporting the shape of the 0th dim at the moment.. Or is there something
> that I'm missing altogether?

This is in keeping with the way that numpy.ndarrays work. Essentially
len and iter treat the array as if it were a list of lists (of lists
...).

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> a
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
>>> a.shape
(4, 2)
>>> len(a)
4
>>> for x in a:
...     print(x)
...
[1 2]
[3 4]
[5 6]
[7 8]

If you want the total number of elements in the array then that is
>>> a.size
8
>>> reduce(lambda x, y: x*y, a.shape, 1)
8

The size attribute is not present on a memoryview but the shape is:
>>> m = memoryview(a)
>>> m.size
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'memoryview' object has no attribute 'size'
>>> m.shape
(4L, 2L)
>>> reduce(lambda x, y: x*y, m.shape, 1)
8L


Oscar



More information about the Python-list mailing list