counting items
Steven Bethard
steven.bethard at gmail.com
Wed Jan 12 13:47:13 EST 2005
Mark McEahern wrote:
> It's me wrote:
>
>> Okay, I give up.
>>
>> What's the best way to count number of items in a list [that may
>> contain lists]?
>>
>>
> a = [[1,2,4],4,5,[2,3]]
>
> def iterall(seq):
> for item in seq:
> try:
> for subitem in iterall(item):
> yield subitem
> except TypeError:
> yield item
>
> all = [x for x in iterall(a)]
> print len(all)
>
Beware:
py> list(iterall(['a']))
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 4, in iterall
...
File "<interactive input>", line 4, in iterall
RuntimeError: maximum recursion depth exceeded
You need to special-case strings. I would do this explicitly, e.g.:
py> def iterall(seq):
... for item in seq:
... if isinstance(item, basestring):
... yield item
... else:
... try:
... for subitem in iterall(item):
... yield subitem
... except TypeError:
... yield item
...
py> list(iterall(['a']))
['a']
but you can also do this by checking for __iter__ as in one of the other
posted solutions. (This takes advantage of the fact that strings use
the __getitem__ protocol for iteration instead of __iter__.)
Steve
More information about the Python-list
mailing list