counting items

It's me itsme at
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,


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:

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

but that's so C-like...


More information about the Python-list mailing list