473,657 Members | 2,805 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

counting items

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)

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.

I tried:

g=lambda x: (1,len(x))[isinstance(x,(l ist,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)

I can, of course:

i=0
for x in a:
if isinstance(x,(l ist,tuple,dict) ):
i += len(x)
else:
i += 1

but that's so C-like...

Thanks,
Jul 18 '05 #1
16 1891
"It's me" <it***@yahoo.co m> wrote in message
news:uk******** *********@newss vr21.news.prodi gy.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(totalle n, x))
return 1
Jul 18 '05 #2
"It's me" <it***@yahoo.co m> wrote in message
news:uk******** *********@newss vr21.news.prodi gy.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
Jul 18 '05 #3
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)

Jul 18 '05 #4
Thanks.

May be flatten should be build into the language somehow....
"Paul McGuire" <pt***@austin.r r._bogus_.com> wrote in message
news:aK******** *********@fe1.t exas.rr.com...
"It's me" <it***@yahoo.co m> wrote in message
news:uk******** *********@newss vr21.news.prodi gy.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

Jul 18 '05 #5
Oh, darn. I asked this kind of question before. <plonk, plonk>

Somebody posted an answer before:

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

data = [[1,5,2],8,4]
val_to_pos = {}
for i, x in enumerate(flatt en(data)):
val_to_pos[x] = i + 1
print val_to_pos

"It's me" <it***@yahoo.co m> wrote in message
news:uk******** *********@newss vr21.news.prodi gy.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)

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.

I tried:

g=lambda x: (1,len(x))[isinstance(x,(l ist,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)

I can, of course:

i=0
for x in a:
if isinstance(x,(l ist,tuple,dict) ):
i += len(x)
else:
i += 1

but that's so C-like...

Thanks,

Jul 18 '05 #6
On Wed, 12 Jan 2005 17:42:50 GMT, It's me <it***@yahoo.co m> 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,(l ist,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,fl oat]]
print listLengths

compoundLength = len(compoundLis t) - 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?!
aN************@ gmAiL.CoM
-----------------------------------------------------
Jul 18 '05 #7
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(flatt en(data))])

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

"Mark McEahern" <ma*******@mcea hern.com> wrote in message
news:ma******** *************** *************** @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)

Jul 18 '05 #8
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 "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 4, in iterall
...
File "<interacti ve 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
Jul 18 '05 #9
"It's me" <it***@yahoo.co m> writes:
May be flatten should be build into the language somehow....


That shouldn't be necessary as it can easily be written in a single list
comprehension:

a = [[1,2,4],4,5,[2,3]]
flat_a = [x for cur, rest in [[a[:1], a[1:]]] for x in cur
if (not isinstance(x, (list, tuple))
and (not rest or not cur.append(rest .pop(0)))
or (x and (cur.append(x[0]) or rest.__setslice __(0, 0, x[1:])))
or (not x and rest and cur.append(rest .pop(0))))]

;-)

Bernhard

--
Intevation GmbH http://intevation.de/
Skencil http://skencil.org/
Thuban http://thuban.intevation.org/
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1376
by: Andrew Banks | last post by:
I have a table of product orders. It contains a row for "platform" and I need to return how many times each platform is listed in the DB Example data for platform could be: XBOX XBOX XBOX PLAYSTATION PLAYSTATION GAMECUBE
4
10428
by: Rob Meade | last post by:
Hi all, Ok - I appreciated I could probably just do this : For Each item IN array intCount = intCount + 1 Next
1
1022
by: zishiri | last post by:
My Operating System is Windows XP. I use Ms Access 2003 My problems are as follows 1. I want a textbox of one form(form2) to count the number of items in one database table and display the number in the textbox of another database table of another form(form1)
3
1224
by: jas2803 | last post by:
Hello, I have a table: The person gets to come back as often as possible and choose between 3 different items, A, B C, for the column. They can take as many as they want, column. I want a query that groups by id, giving me a count of A., Count of B and Count of C choices. Then I want to have a sum of each quantity. I am not able to figure out how to get a count of each choice type per ID. Any ideas? Please and Thanks
4
2419
prn
by: prn | last post by:
Hi folks, I've got another (inherited) puzzle that I don't understand. A report that I need to modify contains a subreport that lists a variable number of items in its detail section and then has a footer which contains a count of those items. That is, the "detail" section of the main report consists of a page for each sub-category listing the items in that category and then includes a count of the items for that sub-category. The way...
0
8403
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8833
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8737
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8509
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8610
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7345
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6174
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1730
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.