counting items

It's me itsme at yahoo.com
Wed Jan 12 18:42:50 CET 2005


Okay, I give up.

What's the best way to count number of items in a list?

For instance,

a=[[1,2,4],4,5,[2,3]]

I want to know how many items are there in a (answer should be 7 - I don't
want it to be 4)

I tried:

b=len([x for y in a for x in y])

That doesn't work because you would get an iteration over non-sequence.

I tried:

g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))]
b=sum(lambda(x) for x in a)

and that didn't work because I get a TypeError from the len function (don't
know why)

I can, of course:

i=0
for x in a:
    if isinstance(x,(list,tuple,dict)):
        i += len(x)
    else:
        i += 1

but that's so C-like...

Thanks,





More information about the Python-list mailing list