473,574 Members | 2,313 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Yield

Hi.

may someone explain "yield" function, please. how does it actually work
and when do you use it?

thanks in forward

mateusz

Nov 15 '06 #1
22 2191
Mateuszk87 wrote:
may someone explain "yield" function, please. how does it actually work
and when do you use it?
it returns a value from a function without actually terminating the
function; when the function is resumed, it'll continue to execute after
the yield.

a function that contains a yield statement is called a "generator" , and
is most often used in a for-in loop, or in other contexts that expect a
sequence. the loop is automatically terminated when the function
returns in a usual way:
>>def gen():
.... yield 1
.... yield 2
.... yield 3
....
>>for item in gen():
.... print item
....
1
2
3
>>sum(gen())
6
>>[str(i) for i in gen()]
['1', '2', '3']

you can also use the generator "by hand"; when you call a generator
function, it returns a special "generator object", and then immediately
suspends itself. to run the generator, call its "next" method:
>>g = gen()
g
<generator object at 0x00AE64E0>
>>g.next()
1
>>g.next()
2
>>g.next()
3

when the generator is exhausted, it raises a StopIterator exception:
>>g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

reference information:

http://effbot.org/pyref/yield.htm

hope this helps!

</F>

Nov 15 '06 #2
Fredrik Lundh wrote:
reference information:
also see:

http://effbot.org/pyfaq/what-is-a-generator.htm

</F>

Nov 15 '06 #3
On Wed, 2006-11-15 at 09:13 -0800, Mateuszk87 wrote:
Hi.

may someone explain "yield" function, please. how does it actually work
and when do you use it?
[There is probably a much better explanation of this somewhere on the
net already, but I feel like writing this out myself.]

"yield" is a keyword. In simple terms, if "yield" appears inside a
function, the function becomes a generator that can return multiple
results.

Consider the following trivial example of a function that calculates the
elements of some sequence and prints each one.

def squares(n):
for i in range(n):
print i**2

Now suppose it turns out that in addition to--or instead of--printing
the elements of this sequence, the caller wants to do something
different with them. You could handle this by building a list, and
return the list to the caller to loop over and operate on as they
choose. But if the list is very big, that's not very memory-efficient if
the caller only needs to operate on one element at a time.

This is where yield comes in. If you write this:

def squares(n):
for i in range(n):
yield i**2

squares is now a generator function. If you call squares(100), it won't
calculate any sequence elements immediately. It will instead return an
iterator the caller can loop over:

for el in squares(100):
print el # or do anything else the caller decides

The beauty of this is that you achieve physical separation between
generating elements of a sequence and using them. The generator function
only cares about how to produce the elements, and the caller only cares
about how to use them.

Hope this helps,

Carsten.
Nov 15 '06 #4
thx for the quick answer. i ll have a look.

Nov 15 '06 #5
Thank you. This is very clear. I can see that this is useful in lots
of situations.

Fredrik Lundh wrote:
Mateuszk87 wrote:
may someone explain "yield" function, please. how does it actually work
and when do you use it?

it returns a value from a function without actually terminating the
function; when the function is resumed, it'll continue to execute after
the yield.

a function that contains a yield statement is called a "generator" , and
is most often used in a for-in loop, or in other contexts that expect a
sequence. the loop is automatically terminated when the function
returns in a usual way:
>>def gen():
... yield 1
... yield 2
... yield 3
...
>>for item in gen():
... print item
...
1
2
3
>>sum(gen())
6
>>[str(i) for i in gen()]
['1', '2', '3']

you can also use the generator "by hand"; when you call a generator
function, it returns a special "generator object", and then immediately
suspends itself. to run the generator, call its "next" method:
>>g = gen()
>>g
<generator object at 0x00AE64E0>
>>g.next()
1
>>g.next()
2
>>g.next()
3

when the generator is exhausted, it raises a StopIterator exception:
>>g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

reference information:

http://effbot.org/pyref/yield.htm

hope this helps!

</F>
Nov 15 '06 #6
Mateuszk87 wrote:
Hi.

may someone explain "yield" function, please. how does it actually work
and when do you use it?

thanks in forward

mateusz
http://docs.python.org/ref/yield.html
Nov 16 '06 #7

dwelch91 a écrit :
http://docs.python.org/ref/yield.html
This is a perfect example that demonstrate how the actual python is bad
and most of the time useless (at least for me).

We really need mor example !

I would like to thanks Fredrik for his contribution to improve that.

Olivier.

Nov 16 '06 #8
On 16/11/2006 5:45 PM, olive wrote:
dwelch91 a écrit :
>http://docs.python.org/ref/yield.html

This is a perfect example that demonstrate how the actual python is bad
and most of the time useless (at least for me).
I think that you left the word "documentat ion" out after "python" :-)
>
We really need mor example !

I would like to thanks Fredrik for his contribution to improve that.
Call me crazy, but after an admittedly quick read, the version on the
wiki seems to be about word for word with on the docs.python.org version.

Could you please tell us how you think the wiki version is an improvement?

Cheers,
John
Nov 16 '06 #9
olive wrote:
>http://docs.python.org/ref/yield.html

This is a perfect example that demonstrate how the actual python is bad
and most of the time useless (at least for me).
there's a place for (relatively) formal reference documentation, but
it's hardly ever the right place to learn why things are there, or how
they are supposed to be used.
We really need mor example !

I would like to thanks Fredrik for his contribution to improve that.
thanks!

(for the curious, my current plan is to use

http://effbot.org/zone/idea-seealso.htm

files to link from the official documentation to tutorials, example
collections, and blog articles. I encourage content producers to start
looking into generating such files for their document collections.)

</F>

Nov 16 '06 #10

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

Similar topics

2
8732
by: yyhhjj | last post by:
I created a test program to implement an iterator. First, I used 'yield break' in the iterator, it worked normally. Then, I simply used 'break' in the places of 'yield break', it still worked normally. What's the difference between 'yield break' and 'break' here? Thanks!
2
7371
by: IntraRELY | last post by:
I know this isnt really a VB question per say, but is what I am developing in VB.NET and Excel is the only place that has provided direction. I wanted to ask the public if perhaps you could lend me a hand a point me into the right direction if there is someone who has had experiance with this. By all means if you know a better place to ask,...
3
3515
by: andy.leszczynski | last post by:
Hi, I might understand why this does not work, but I am not convinced it should not - following: def nnn(): print 'inside' yield 1 def nn():
3
6919
by: Ehsan | last post by:
hi coulde any one show me the usage of "yield" keyword specially in this example: """Fibonacci sequences using generators This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version.
6
1525
by: Shriphani | last post by:
Hello all, Let us say I have a function like this: def efficientFiller(file): worthless_list = pot_file = open(file,'r') pot_file_text = pot_file.readlines() for line in pot_file_text: if line.find("msgid") != -1:
1
1069
by: castironpi | last post by:
What if I say oath= yield or other= yield ?
13
1802
by: Martin Sand Christensen | last post by:
Hi! First a bit of context. Yesterday I spent a lot of time debugging the following method in a rather slim database abstraction layer we've developed: ,---- | def selectColumn(self, table, column, where={}, order_by=, group_by=): | """Performs a SQL select query returning a single column
7
1503
by: Alex Bryan | last post by:
Okay, so i don't really understand the Yield thing and i know it is useful. I've read a few things about it but it is all programming jargon and so basically it is hard for me to understand. So can anyone give me a description or link me to a site that has a good definition and/or examples of it? If you could I would really appreciate it.
5
1133
by: defn noob | last post by:
def letters(): a = xrange(ord('a'), ord('z')+1) B = xrange(ord('A'), ord('Z')+1) while True: yield chr(a) yield chr(B) Traceback (most recent call last):
0
7797
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7715
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...
0
8041
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. ...
0
8225
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...
0
8093
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...
0
6440
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5611
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3739
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2233
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

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.