dumping generator

T

targetsmart

Right now if I want to dump the contents of a generator object I use ,
a snip from a bigger block of code..

try:
while gen: print gen.next()
except StopIteration:
print "Done"
else:
raise

is there a much simpler way ?

like for printing list we do
list = range(10)
print list
would print
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
P

Peter Otten

targetsmart said:
Right now if I want to dump the contents of a generator object I use ,
a snip from a bigger block of code..

try:
while gen: print gen.next()
except StopIteration:
print "Done"
else:
raise

is there a much simpler way ?

Indeed there is:

for item in gen:
print item
print "Done"

Peter
 
U

Ulrich Eckhardt

targetsmart said:
Right now if I want to dump the contents of a generator object I use ,
a snip from a bigger block of code..

try:
while gen: print gen.next()
except StopIteration:
print "Done"
else:
raise

is there a much simpler way ?

Why not something like this:

for i in gen:
print i
like for printing list we do
list = range(10)
print list
would print
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You could coerce the thing into a list:

gen = xrange(10)
print list(gen)

:)

Uli
 
R

Rob Williscroft

targetsmart wrote in @i18g2000pro.googlegroups.com in gmane.comp.python.general:
Right now if I want to dump the contents of a generator object I use ,
a snip from a bigger block of code..

try:
while gen: print gen.next()
except StopIteration:
print "Done"
else:
raise

is there a much simpler way ?

print list( gen )
like for printing list we do
list = range(10)
print list
would print
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top