- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What does the “yield” keyword do in Python?
The yield keyword is used in generator. To understand its behaviour let us first see what are iterables. Python objects list, file, string etc are called iterables. Any object which can be traversed using for .. in syntax is iterable. Iterator object is also an iterable, but it can be iterated upon only once. Iterator object can be obtained form any iterable using iter() function and it has next() method using which iteration is done.
>>> L1 = [1,2,3,4] >>> I1 = iter(L1) >>> while True: try: print (next(I1)) except StopIteration: sys.exit()
The generator appears similar to a function, but it yields successive items in the iterator by yield keyword.
When a generator function is called, it returns a iterator object without even beginning execution of the function. When the next() method is called for the first time, the function starts executing until it reaches the yield statement, which returns the yielded value. The yield keeps track i.e. remembers the last execution and the second next() call continues from previous value.
Following example generates an iterator containing numbers in Fibonacci series. Each call to generator function fibo() yields successive element in the Fibonacci series.
import sys def fibo(n): a,b=0,1 while True: if a>n : return yield a a, b = b, a+b f = fibo(20) while True: try: print (next(f)) except StopIteration: sys.exit()
- “extern” keyword in C
- “register” keyword in C
- What does a “set+0” in a MySQL statement do?
- What does “?:” mean in a Python regular expression?
- What does the keyword var do in C#?
- How does “do something OR DIE()” work in Perl?
- Does Python have “private” variables in classes?
- Yield keyword in Ruby Programming
- What does an auto keyword do in C++?