I am new to Python. I just came across generators in Python. But I  am not able to understand it completely. Can anyone explain to me it in simple words? Jul 11, 2019 in Python 29 views

## 1 answer to this question.

There are two terms involved when we discuss generators.

1. Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
2. Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop
So a generator function returns a generator object that is iterable, i.e., can be used as an Iterator

# A simple generator for Fibonacci Numbers
def fib(limit):

# Initialize first two Fibonacci Numbers
a, b = 0, 1

# One by one yield next Fibonacci Number
while a < limit:
yield a
a, b = b, a + b

# Create a generator object
x = fib(5)

# Iterating over the generator object using next
print(x.next()); # In Python 3, __next__()
print(x.next());
print(x.next());
print(x.next());
print(x.next());

# Iterating over the generator object using for
# in loop.
print("\nUsing for in loop")
for i in fib(5):
print(i)

Output :

0
1
1
2
3

Using for in loop
0
1
1
2
3 answered Jul 11, 2019 by
• 3,010 points

## what are "and" and "or" operators in Python?

AND - True if both the operands ...READ MORE

## What are the types of dictionary in python?

There are 4 types of dictionary Empty Integer Mixed Dictionary with ...READ MORE

+1 vote

## What are the ways of detecting outliners in Python

code from http://eurekastatistics.com/using-the-median-absolute-deviation-to-find-outliers  This uses the L1 distance ...READ MORE

## What are metaclasses in Python?

A metaclass instantiates and defines behavior for ...READ MORE

## how do i change string to a list?

suppose you have a string with a ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

## how do i use the enumerate function inside a list?

can you give an example using a ...READ MORE