Junior — Middle
Explain what the use of the keyword 'Yield' means in programming and how it works
sobes.tech AI
Answer from AI
The keyword yield is used in programming languages (for example, Python) to create generators — functions that return a sequence of values one at a time, pausing their execution between calls.
When a function with yield is called, it does not execute fully immediately but returns a generator — an iterator. Each time the next() method is called, the function resumes execution from the last yield and continues until the next yield or the end of the function.
This allows efficient handling of large data volumes without loading the entire sequence into memory at once.
Example in Python:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
Here, the count_up_to function returns numbers from 1 to n one at a time, using yield.