Skip to content

Commit 988c6a3

Browse files
nils-wernermrocklin
authored andcommitted
len() function for COO objects (#68)
* len() function for COO objects * Docstrings and tests * Fixed docstring typo
1 parent 49f6479 commit 988c6a3

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

sparse/core.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,29 @@ def nnz(self):
253253
def nbytes(self):
254254
return self.data.nbytes + self.coords.nbytes
255255

256+
def __len__(self):
257+
"""
258+
Get "length" of array, which is by definition the size of the first
259+
dimension.
260+
261+
Returns
262+
-------
263+
int
264+
The size of the first dimension.
265+
266+
See Also
267+
--------
268+
numpy.ndarray.__len__ : Numpy equivalent property.
269+
270+
Examples
271+
--------
272+
>>> x = np.zeros((10, 10))
273+
>>> s = COO.from_numpy(x)
274+
>>> len(s)
275+
10
276+
"""
277+
return self.shape[0]
278+
256279
def __sizeof__(self):
257280
return self.nbytes
258281

sparse/tests/test_core.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -875,3 +875,8 @@ def test_scalar_shape_construction():
875875
s = COO(coords, x, shape=5)
876876

877877
assert_eq(x, s)
878+
879+
880+
def test_len():
881+
s = sparse.random((20, 30, 40))
882+
assert len(s) == 20

0 commit comments

Comments
 (0)