counting items

It's me itsme at yahoo.com
Wed Jan 12 13:42:24 EST 2005


Yes, Mark, I came up with almost the same code (after reading back old
answers from this list):

def flatten(seq):
    for x in seq:
        if hasattr(x, "__iter__"):
            for subx in flatten(x):
                yield subx
        else:
            yield x

def count_item(data):
    return len([(i,x) for i, x in enumerate(flatten(data))])

data = [[1,5,2],8,4]
print count_item(data)


Thanks everybody.



"Mark McEahern" <marklists at mceahern.com> wrote in message
news:mailman.579.1105554265.22381.python-list at python.org...
> 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)
>





More information about the Python-list mailing list