Difference between yield in Python and yield in C#

Question:

What is the difference between yield keyword in Python and yield keyword in C#?

Asked By: maxyfc

||

Answers:

C#’s yield return is equivalent to Python’s yield , and yield break is just return in Python.

Other than those minor differences, they have basically the same purpose.

Answered By: John Millikin

The most important difference is that python yield gives you an iterator, once it is fully iterated that’s over.

But C# yield return gives you an iterator “factory”, which you can pass it around and uses it in multiple places of your code without concerning whether it has been “looped” once before.

Take this example in python:

In [235]: def func1():
   .....:     for i in xrange(3):
   .....:         yield i
   .....:

In [236]: x1 = func1()

In [237]: for k in x1:
   .....:     print k
   .....:
0
1
2

In [238]: for k in x1:
   .....:     print k
   .....:

In [239]:

And in C#:

class Program
{
    static IEnumerable<int> Func1()
    {
        for (int i = 0; i < 3; i++)
            yield return i;
    }

    static void Main(string[] args)
    {
        var x1 = Func1();
        foreach (int k in x1) 
            Console.WriteLine(k);

        foreach (int k in x1)
            Console.WriteLine(k);
    }
}

That gives you:

0
1
2
0
1
2
Answered By: Paul

An important distinction to note, in addition to other answers, is that yield in C# can’t be used as an expression, only as a statement.

An example of yield expression usage in Python (example pasted from here):

def echo(value=None):
  print "Execution starts when 'next()' is called for the first time."
  try:
    while True:
       try:
         value = (yield value)
       except GeneratorExit:
         # never catch GeneratorExit
         raise
       except Exception, e:
         value = e
     finally:
       print "Don't forget to clean up when 'close()' is called."

generator = echo(1)
print generator.next()
# Execution starts when 'next()' is called for the first time.
# prints 1

print generator.next()
# prints None

print generator.send(2)
# prints 2

generator.throw(TypeError, "spam")
# throws TypeError('spam',)

generator.close()
# prints "Don't forget to clean up when 'close()' is called."
Answered By: Max Desiatov
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.