views:

96

answers:

2

I want to define a generator from a list that will output the elements one at a time, then use this generator object in an appropriate manner.

a = ["Hello", "world", "!"]
b = (x for x in a)
c = next(b, None)
while c != None:
    print c,
    c = next(b, None)

Is there anything wrong or improvable with the while approach here? Is there a way to avoid having to assign 'c' before the loop?

Thanks!

+7  A: 

Why would you use a while loop? In Python, for loops are absolutely designed for this:

a = ["Hello", "world", "!"]
b = (x for x in a)
for c in b:
    print c,

If you are stuck on a while implementation for whatever reason, your current implementation is probably the best you can do, but it's a bit clunky, don't you think?

Daniel G
Of course. I don't know why I imagined that generators I create behave any different then the implemented ones. X_X
Morlock
+3  A: 

Clarification: you meant generator expressions not generators -- the latter is a function definition that contains at least one yield statement/expression.

agreed with the earlier poster... you should be using for loops for almost everything. i rarely use while loops, which are relegated to simple counters or servers running infinite loops. :-)

you can also put the genexp on the same line as the for loop...

a = ["Hello", "world", "!"]
for c in (x for x in a):
    print c,

...since the genexp can't be reused. however, it doesn't look as readable. also, this defeats the purpose of this exercise. why not just iterate over a itself?

for c in ["Hello", "world", "!"]:
    print c,

you've already used up memory to make the list; why create a genexp when it's not nec?

wescpy
Very elegant approach. As to "why not iterate over the list", the aim of the exercise was to learn to use this for cases where the list is both HUGE (maybe 1 Go) and there are operations to be made on the objects (maybe from more than one list too). So by this approach, I avoid creating another huge list.
Morlock
yup, agreed. in fact, i try to encourage ppl not to create the 1st list (or any lists) to begin with! if you can just start off with an iterator, generator, or genexp to begin with, you've already won! :-) this will be some sort of blog post or an article on InformIT http://www.informit.com/topics/topic.aspx?st=66503 at some point cuz i've already written most of it.
wescpy