counting items
Bengt Richter
bokr at oz.net
Wed Jan 12 21:45:03 EST 2005
On Wed, 12 Jan 2005 18:07:47 GMT, "Andrew Koenig" <ark at acm.org> wrote:
>"It's me" <itsme at yahoo.com> wrote in message
>news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com...
>
>> 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)
>
>How about this?
>
> def totallen(x):
> if isinstance(x, (list, tuple, dict)):
> return sum(map(totallen, x))
> return 1
Since the requirement is to _count_, not flatten, ISTM your solution is best so far ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list