counting items

Anthony anthony.briggs at gmail.com
Wed Jan 12 13:33:13 EST 2005


On Wed, 12 Jan 2005 17:42:50 GMT, It's me <itsme at yahoo.com> wrote:
> Okay, I give up.
> 
> What's the best way to count number of items in a list?

How long is a piece of string? There are many different ways, which
give you different trade offs.

> 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)
> 
> 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.

And is very unreadable.

> 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)

Because you're trying to get the length of an integer, which is what's failing.

If you know that the list nesting is only one deep, you can do something like:

===
#!/usr/local/bin/python

compoundList = [[1,2,4],4,5,[2,3]]

listLengths = [len(item) for item in compoundList if type(item) not in
[int,long,str,float]]
print listLengths

compoundLength = len(compoundList) - len(listLengths) + sum(listLengths)
print compoundLength
===

If the nesting is 2 deep or more, then the next two options that I
would explore would be:

1. Have a look in the standard library. I'm pretty sure that there are
list-manipulation libraries that'll do what you want (not sure on
names, though).
2. Write a function to do what you want. Some sort of recursive thing
should be pretty easy to write. Of course it depends on how fast you
need to go, but that should give you a good first approximation.

Anthony

-- 
-----------------------------------------------------
 HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?!
 aNthONy.BrIGgS at gmAiL.CoM
-----------------------------------------------------



More information about the Python-list mailing list