Python Generators

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Generators are function used to create iterators, so that it can be used in the for loop.

Creating Generators

Generators are defined similar to function but there is only one difference, we use yield  keyword to return value used for each iteration of the for loop. Let’s see an example where we are trying to clone python’s built-in range()  function.

Expected Output:

Here is how my_range()  works:

In for loop my_range()  function get called, it initializes values of the three arguments( start , stop  and step ) and also checks whether stop  is smaller than or equal to start , if it is not then i  is assigned value of start . At this point i  is 10 so while condition evaluates to True  and while loop starts executing. In next statement yield transfer control to the for loop and assigns current value of i to variable k , inside the for loop print statement get executed, then the control again passes to line 7 inside the function my_range()  where i  gets incremented. This process keeps on repeating until i < stop .

Other Tutorials

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

2 Comments on "Python Generators"

Notify of

Sort by:   newest | oldest | most voted
1 year 11 months ago

def my_range(start, stop, step = 1):
if stop <= start:
raise RuntimeError("start must be smaller than stop")
i = start
while i < stop:
yield i
i += step

You miss a tab.

1 year 11 months ago

OK I cannot keep my tabs in comment, and currently I noticed the code have been corrected.