473,809 Members | 2,758 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

itertools.ilen?

Sometimes I find myself simply wanting the length of an iterator. For
example, to collect some (somewhat useless ;)) statistics about a program
of mine, I've got code like this:

objs = gc.get_objects( )
classes = len([obj for obj in objs if inspect.isclass (obj)])
functions = len([obj for obj in objs if inspect.isrouti ne(obj)])
modules = len([obj for obj in objs if inspect.ismodul e(obj)])
dicts = len([obj for obj in objs if type(obj) == types.DictType])
lists = len([obj for obj in objs if type(obj) == types.ListType])
tuples = len([obj for obj in objs if type(obj) == types.TupleType])

Now, obviously I can (and will, now that 2.3 is officially released :))
replace the list comprehensions with itertools.ifilt er, but I need an
itertools.ilen to find the length of such iterators.

I can imagine such a need arises in more useful situations than this, but
this is the particular case that brought the need to mind.

The Python code is simple, obviously:

def ilen(iterator):
i = 0
for _ in iterator:
i += 1
return i

But it's a pity to use itertools' super-fast iterators and have to use slow,
raw Python to determine their length :)

Jeremy
Jul 18 '05 #1
10 3392

"Jeremy Fincher" <fi*******@osu. edu> wrote in message
news:bg******** **@news.cis.ohi o-state.edu...
Sometimes I find myself simply wanting the length of an iterator.
An iterator is a function/method that traverses (or possibly
generates) a seqeuence. The sequence has a length (actual or
potential) but the iterator does not.
For example, to collect some (somewhat useless ;))
statistics about a program of mine, I've got code like this:

objs = gc.get_objects( )
classes = len([obj for obj in objs if inspect.isclass (obj)])
functions = len([obj for obj in objs if inspect.isrouti ne(obj)]) modules = len([obj for obj in objs if inspect.ismodul e(obj)]) dicts = len([obj for obj in objs if type(obj) == types.DictType]) lists = len([obj for obj in objs if type(obj) == types.ListType]) tuples = len([obj for obj in objs if type(obj) == types.TupleType])

Alternative: initialize six counters to 0. Scan list once and update
appropriate counter.
Now, obviously I can (and will, now that 2.3 is officially released :)) replace the list comprehensions with itertools.ifilt er, but I need an itertools.ilen to find the length of such iterators.
You mean the associated sequence.
I can imagine such a need arises in more useful situations than this, but this is the particular case that brought the need to mind.

The Python code is simple, obviously:

def ilen(iterator):
i = 0
for _ in iterator:
i += 1
return i

But it's a pity to use itertools' super-fast iterators and have to use slow, raw Python to determine their length :)


If you mean a c-coded counter (which would not be an iterator itself)
equivalent to the above, that could be done. Perhaps len() could be
upgraded/extended to accept an iterator and count when it can't get a
__len__ method to call. The main downside is that iterators are
sometimes destructive (run once only).

In the meanwhile, is this really a bottleneck for you? or merely the
'pity' of a program running in 1 sec when 0.1 is possible?

Terry J. Reedy
Jul 18 '05 #2

"Terry Reedy" <tj*****@udel.e du> schrieb im Newsbeitrag
news:tp******** ************@co mcast.com...

"Jeremy Fincher" <fi*******@osu. edu> wrote in message
news:bg******** **@news.cis.ohi o-state.edu...
Sometimes I find myself simply wanting the length of an iterator.


An iterator is a function/method that traverses (or possibly
generates) a seqeuence. The sequence has a length (actual or
potential) but the iterator does not.


Very well explained. There are lots of usefull generators with unlimited
sequences.

- random generators

- def achilles():
while 1
:N=1.
yield N
n=n/2

- def schoenberg():
cycle=range(12)
while 1:
shuffle(cycle)
for i in cycle:
yield i
There is no way to determined, whether such generartors will come to an
end - The Halting Problem for Turing Machines ;-)
Thus there will never be a safe len(iterator).

Kindly
Michael
Jul 18 '05 #3
Terry Reedy wrote:
An iterator is a function/method that traverses (or possibly
generates) a seqeuence. The sequence has a length (actual or
potential) but the iterator does not.
Even some sequences don't have a length; consider (Lisp terminology)
"improper lists," where the cdr points to a cell earlier in the list. Or
any class with a somehow non-terminating __len__.
Alternative: initialize six counters to 0. Scan list once and update
appropriate counter.
Yes, that works in this particular case, and is probably a superior
solution.
If you mean a c-coded counter (which would not be an iterator itself)
equivalent to the above, that could be done. Perhaps len() could be
upgraded/extended to accept an iterator and count when it can't get a
__len__ method to call. The main downside is that iterators are
sometimes destructive (run once only).
That's why I don't think such a change should be made to len(); *all*
iterators are destructive and len() silently destroying them doesn't seem
generally useful enough for the potential for mistake.
In the meanwhile, is this really a bottleneck for you? or merely the
'pity' of a program running in 1 sec when 0.1 is possible?


The whole of itertools really seems to exist because of the "pity" of taking
efficient iterators and turning them into lists in order to do any
significant manipulation of them. In that case, I would imagine the pity
of having to turn an interator into a sequence in order to determine the
length of the underlying sequence would be reason enough.

Jeremy

Jul 18 '05 #4
Michael Peuser wrote:
There is no way to determined, whether such generartors will come to an
end - The Halting Problem for Turing Machines ;-)
Thus there will never be a safe len(iterator).


But then, there's no way to determine whether any given class' __len__ will
terminate, so you've got the same problem with len.

Granted, it's more likely to manifest itself with iterators and ilen than
with sequences and len, but if it's really an issue, ilen could take an
optional "max" argument for declaring a counter ilen isn't to exceed.

Jeremy
Jul 18 '05 #5
Another solution could be to implement custom lenght methods. However I see
no graceful way to do it with the quite tricky implementation (yield is the
only hint!) of 2.3.

It would be definitly easy with 2.2 "by hand" function factories (def
iter(), def __next__()), just def len() in addition and find the fastest
implementation

Kindly
Michael

"Jeremy Fincher" <fi*******@osu. edu> schrieb im Newsbeitrag
news:bg******** **@news.cis.ohi o-state.edu...
Michael Peuser wrote:
There is no way to determined, whether such generartors will come to an
end - The Halting Problem for Turing Machines ;-)
Thus there will never be a safe len(iterator).
But then, there's no way to determine whether any given class' __len__

will terminate, so you've got the same problem with len.

Granted, it's more likely to manifest itself with iterators and ilen than
with sequences and len, but if it's really an issue, ilen could take an
optional "max" argument for declaring a counter ilen isn't to exceed.

Jeremy

Jul 18 '05 #6
"Jeremy Fincher"
Sometimes I find myself simply wanting the length of an iterator. For
example, to collect some (somewhat useless ;)) statistics about a program
of mine, I've got code like this:

objs = gc.get_objects( )
classes = len([obj for obj in objs if inspect.isclass (obj)])
functions = len([obj for obj in objs if inspect.isrouti ne(obj)])
modules = len([obj for obj in objs if inspect.ismodul e(obj)])
dicts = len([obj for obj in objs if type(obj) == types.DictType])
lists = len([obj for obj in objs if type(obj) == types.ListType])
tuples = len([obj for obj in objs if type(obj) == types.TupleType])

Now, obviously I can (and will, now that 2.3 is officially released :))
replace the list comprehensions with itertools.ifilt er, but I need an
itertools.ilen to find the length of such iterators.

I can imagine such a need arises in more useful situations than this, but
this is the particular case that brought the need to mind.

The Python code is simple, obviously:

def ilen(iterator):
i = 0
for _ in iterator:
i += 1
return i

But it's a pity to use itertools' super-fast iterators and have to use slow,
raw Python to determine their length :)

For your application, it is not hard to build a itertools version:
import itertools
def countif(predica te, seqn): .... return sum(itertools.i map(predicate, seqn))
def isEven(x): .... return x&1 == 0
countif(isEven, xrange(1000000) ) 500000
def isTuple(x): .... return type(x) == types.TupleType
tuples = countif(isTuple , objs)

Raymond Hettinger
Jul 18 '05 #7
On Thu, 07 Aug 2003 03:10:10 -0400, rumours say that Jeremy Fincher
<fi*******@osu. edu> might have written:
objs = gc.get_objects( )
classes = len([obj for obj in objs if inspect.isclass (obj)])
functions = len([obj for obj in objs if inspect.isrouti ne(obj)])
modules = len([obj for obj in objs if inspect.ismodul e(obj)])
dicts = len([obj for obj in objs if type(obj) == types.DictType])
lists = len([obj for obj in objs if type(obj) == types.ListType])
tuples = len([obj for obj in objs if type(obj) == types.TupleType])


Another way to count objects:

# code start
import types, gc

type2key = {
types.ClassType : "classes",
types.FunctionT ype: "functions" ,
types.MethodTyp e: "functions" ,
types.ModuleTyp e: "modules",
types.DictType: "dicts",
types.ListType: "lists",
types.TupleType : "tuples"
}

sums = {
"classes": 0, "functions" : 0, "modules": 0, "dicts": 0,
"lists": 0, "tuples": 0
}

for obj in gc.get_objects( ):
try:
sums[type2key[type(obj)]] += 1
except KeyError:
pass
# code end

This code is intended to be <2.3 compatible.
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #8
Christos "TZOTZIOY" Georgiou <tz**@sil-tec.gr> wrote in
news:98******** *************** *********@4ax.c om:
Another way to count objects:

# code start
import types, gc

type2key = {
types.ClassType : "classes",
types.FunctionT ype: "functions" ,
types.MethodTyp e: "functions" ,
types.ModuleTyp e: "modules",
types.DictType: "dicts",
types.ListType: "lists",
types.TupleType : "tuples"
}

sums = {
"classes": 0, "functions" : 0, "modules": 0, "dicts": 0,
"lists": 0, "tuples": 0
}

for obj in gc.get_objects( ):
try:
sums[type2key[type(obj)]] += 1
except KeyError:
pass
# code end


I'm just curious, why did you decide to map the types to strings instead of
just using the types themselves?
e.g.
import gc
sums = {}
for obj in gc.get_objects( ): if type(obj) not in sums:
sums[type(obj)] = 1
else:
sums[type(obj)] += 1

for typ, count in sums.iteritems( ): print typ.__name__, count
instance 525
tuple 4273
class 162
getset_descript or 14
traceback 2
wrapper_descrip tor 165
list 258
module 71
instance method 279
function 1222
weakref 18
dict 1647
method_descript or 82
member_descript or 75
frame 18


--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #9
Duncan Booth wrote:
I'm just curious, why did you decide to map the types to strings instead
of just using the types themselves?


So I can pluralize them in my output.

Jeremy

Jul 18 '05 #10

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

Similar topics

1
2304
by: Dan Williams | last post by:
Is there any interest in adding a "Haskellish" take function to itertools? I know its easy enough to roll my own, I've been using: take = lambda iter, n: which works, but I was wondering if it was common enough to get into itertools? -Dan
6
1745
by: Robert Brewer | last post by:
def warehouse(stock, factory=None): """warehouse(stock, factory=None) -> iavailable, iremainder. Iterate over stock, yielding each value. Once the 'stock' sequence is exhausted, the factory function (or any callable, such as a class) is called to produce a new valid object upon each subsequent call to next().
1
1281
by: anton muhin | last post by:
Hello, everybody! Trying to solve the problem in the subj, I found that I miss some iterator-related tools. Mostly consequental application of the same function to some argument (if I'm not missing something it has a name y-combinator). If we had one, generating the sequence of digits is easy: iter(y(lambda (q, _): divmod(q, n), (x, 0)).next, (0, 0))
1
3800
by: Steven Bethard | last post by:
Is there a reason that itertools.islice doesn't support None arguments for start and step? This would be handy for use with slice objects: >>> r = range(20) >>> s1 = slice(2, 10, 2) >>> s2 = slice(2, 10) >>> s3 = slice(10) >>> list(itertools.islice(r, s1.start, s1.stop, s1.step)) >>> list(itertools.islice(r, s2.start, s2.stop, s2.step))
18
2640
by: Ville Vainio | last post by:
For quick-and-dirty stuff, it's often convenient to flatten a sequence (which perl does, surprise surprise, by default): ]]] -> One such implementation is at http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2302348
21
2191
by: Steven Bethard | last post by:
Jack Diederich wrote: > > itertools to iter transition, huh? I slipped that one in, I mentioned > it to Raymond at PyCon and he didn't flinch. It would be nice not to > have to sprinkle 'import itertools as it' in code. iter could also > become a type wrapper instead of a function, so an iter instance could > be a wrapper that figures out whether to call .next or __getitem__ > depending on it's argument. > for item in...
41
2687
by: rurpy | last post by:
The code below should be pretty self-explanatory. I want to read two files in parallel, so that I can print corresponding lines from each, side by side. itertools.izip() seems the obvious way to do this. izip() will stop interating when it reaches the end of the shortest file. I don't know how to tell which file was exhausted so I just try printing them both. The exhausted one will generate a
23
1472
by: Mathias Panzenboeck | last post by:
I wrote a few functions which IMHO are missing in python(s itertools). You can download them here: http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104 A short description to all the functions: icmp(iterable1, iterable2) -integer Return negative if iterable1 < iterable2, zero if iterable1 == iterable1,
17
7707
by: Raymond Hettinger | last post by:
I'm considering deprecating these two functions and would like some feedback from the community or from people who have a background in functional programming. * I'm concerned that use cases for the two functions are uncommon and can obscure code rather than clarify it. * I originally added them to itertools because they were found in other functional languages and because it seemed like they would serve basic building blocks in...
0
9601
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10635
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
10376
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
10378
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
10115
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
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.