I have this code:
def generator(n): list_of = range(1,n+1) for i in list_of: if i % 7 == 0: yield iprint generator(100)This should print all the numbers in the given range that are divisible by7, but the output is<generator object generator at 0x1004ad280> instead.
Also, the wordyield in my text editor (KOD) doesn't appear highlighted in sky blue color like all the reserved words but instead appears in white, is that fine?
- It's bug/misfeature in your text editors syntax highlighting.Lennart Regebro– Lennart Regebro2014-05-30 11:50:23 +00:00CommentedMay 30, 2014 at 11:50
- You may also want to have a look at this:stackoverflow.com/q/231767/1025391moooeeeep– moooeeeep2014-05-30 11:57:37 +00:00CommentedMay 30, 2014 at 11:57
3 Answers3
Your generatorworks. You forgot to iterate over it though:
for elem in generator(100): print elemor you could turn it into a list:
print list(generator(100))You instead printed the generator object produced by calling the generator function. A generator function produces asuspended generator. Only when you iterate over it is code executed (until the nextyield).
Demo:
>>> def generator(n):... list_of = range(1,n+1)... for i in list_of:... if i % 7 == 0:... yield i... >>> print list(generator(100))[7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98]Thelist() call iterates over the given argument, producing a Python list object with all elements yielded by the argument. Great for iterating over a generator to pull in all the elements that it produces.
As for KOD; that editor hasn't seen updates in years now; you may want to switch to something else. As theKOD twitter feed stated2 years ago:
Don't wait for me, I'm kind of like a Zombie. Go get Sublime Text@sublimehq which is awesome:http://www.sublimetext.com
I concur; Sublime Text is my current editor of choice.
Comments
Generators functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop. u can learn Here:generator
def generator(n): list_of = range(1,n+1) for i in list_of: if i % 7 == 0: yield i for i in generator(100): print ior
You can usenext(generator(100)) to print one element at top
or
list(generator(100))Comments
When calling the generator function you receive generator object. In order to get values you should iterate over this object. In you case you can dolist(generator(100))
But this doesn't make sense. Use list comprehension if you need list:
[x for x in range(1, 101) if x % 7 == 0]Comments
Explore related questions
See similar questions with these tags.
