iterator wrapper

Simon Forman rogue_pedro at yahoo.com
Sat Aug 12 13:03:30 EDT 2006


alf wrote:
> Simon Forman wrote:
> >>
> >>>|>> I = ([n] for n in i)
> >>
> >>This is nice but I am iterating thru hude objects (like MBs) so you know ...
> >>
> >
> > No, I don't know...  :-)
>
> potentially my source lists are huge - so wanted to avoid unnecessary
> memory allocation
>
>
> > My friend, I think you've misunderstood.  Observe:
> >
> > |>> L = [n for n in range(3)]
> > |>> G = (n for n in range(3))
> > |>> L
> > [0, 1, 2]
> > |>> G
> > <generator object at 0xb7d982ec>
>
> well, I am in the python 2.3 word where generator comprehensions seem
> not to work. So I just took it a preallocated list comprehention. still
> wonder if there would be a difference between:
>
> G = (n for n in range(300000000))  - this creates the huge list there
> G = (n for n in xrange(300000000)) - this (at least to my understanding)
>   does not
>

Yes, you've got it, the xrange() version will not allocate a huge list.

It's not part of your main question, and I understand that there may be
reasons why you can't, but consider upgrading to 2.4 (or very soon now
2.5...)

Meanwhile, in 2.3 both John Machin's and Paul Rubin's solutions will do
the trick (as you already know ;-)  )

> >
> > List comprehensions [] create lists, generator comprehensions () create
> > generators.
> >
>
>
> > Generator comprehensions work "just-in-time", pulling items from
> > whatever they're iterating over as they themselves are iterated over,
> > as I hope this example makes clear:
> >
>  >[...]
>
> got it now ... thx or the lesson....
>
>
> A.

No problem.  These are things I learned over time, it's fun to share
the knowledge. :)

Peace,
~Simon




More information about the Python-list mailing list