# counting items

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

```Thanks.

May be flatten should be build into the language somehow....

"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
news:aKdFd.8991\$RW3.7375 at fe1.texas.rr.com...
> "It's me" <itsme at yahoo.com> wrote in message
> news:ukdFd.10645\$5R.2000 at newssvr21.news.prodigy.com...
> > 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)
> >
> <snip>
>
> I've sure seen a lot of questions about the flattening of lists.  I found
> this version of flatten somewhere, I thought I got it from the Python
> Cookbook but I can't find it now.  Perhaps it was posted here on c.l.py.
I
> *don't* claim authorship, I'm merely an admirer of such a clean-looking
> solution.
>
> def flatten(a):
>     if not isinstance(a, (tuple,list)): return [a]
>     if len(a)==0: return []
>     return flatten(a[0])+flatten(a[1:])
>
> a = [[1, 2, 4], 4, 5, [2, 3], 6, [6], [], 'askjdf']
>
> print len(flatten(a))
>
> gives the value 10.
>
> Considering how often this comes up, might there be a place for some sort
of
> flatten() routine in the std dist, perhaps itertools?
>
> -- Paul
>
>

```