SeaWind
SeaWind

Reputation: 13

Python size() and len() for list of list

I have a list:

a = [[1, 0], 'apple', 5]

Why does size(a[0]) work even though a isn't a numpy array?

I thought size worked only on arrays?

Thanks!

Upvotes: 1

Views: 7330

Answers (1)

DSM
DSM

Reputation: 353604

size[a[0]] shouldn't work, but size(a[0]) should. You can simply look at the source for np.size:

def size(a, axis=None):
    [docstring removed]

    if axis is None:
        try:
            return a.size
        except AttributeError:
            return asarray(a).size
    else:
        try:
            return a.shape[axis]
        except AttributeError:
            return asarray(a).shape[axis]

When you pass a list, axis stays at its default value of None and the function tries to get a.size. Since that doesn't exist, it turns the list into an array using asarray(a) and gets the size that way. In your case, it will make a 1-D numpy array of dtype object.

Upvotes: 3

Related Questions