Your Dashboard
Sign-in
Sign-up
RegularPython
  • Membership
  • RoadMaps
  • Online Tests
    • Online Test
    • Interview Questions
    • Online Store
  • Jobs
    • Student Reviews
    • Mock Interviews
    • Apply for jobs
    • Contact for help
  • Sign-in
  • Sign-up
  1. Home
  2. Python Basic Courses

regularpython@gmail.com

Image

Python generators

  • Category
    Python Generator Function, Yield, Return, RegularPython
  • Course Menu
    • Python Introduction
    • Python Uses
    • Python Features
    • Python Operators
    • Python Data Types
    • Python Numbers
    • Python Strings
    • Python Lists
    • Python Tuples
    • Python Dictionaries
    • Python Sets
    • Python Decision Making
    • Python Loops
    • Python Exceptions
    • Python Functions
    • Python Lambda function
    • Random Numbers in Python
    • Regular Expressions
    • Python Decorators
    • Python generators

Python generators

The generator is also a function. The difference between normal function and generator function is,

Normal functions use the return keyword to exit the function but generator function uses yield keyword to exit the function. We have python functions than what is the use of Generator functions.

The main use of the generator function is, to save the memory space and increase performance.

See the below example what is the exact use of generator function,

Normal Function Example:

def doctor(patients):

    result = []

    for i in patients:

        result.append("patient %s checkup completed "%(i))

    return result

 

patients = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

status = doctor(patients)

print(status)

Output:

['patient 1 checkup completed ', 'patient 2 checkup completed ', 'patient 3 checkup completed ', 'patient 4 checkup completed ', 'patient 5 checkup completed ', 'patient 6 checkup completed ', 'patient 7 checkup completed ', 'patient 8 checkup completed ', 'patient 9 checkup completed ', 'patient 10 checkup completed ']

 

Generator Function Example:

def doctor(patients):

    for i in patients:

        yield "patient %s checkup completed "%(i)

 

patients = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

status = doctor(patients)

print(next(status))

print(next(status))

print("Doctor taking Rest..")

print(next(status))

print(next(status))

print(next(status))

print("Doctor taking Rest..")

print(next(status))

print(next(status))

Output:

patient 1 checkup completed

patient 2 checkup completed

Doctor taking Rest..

patient 3 checkup completed

patient 4 checkup completed

patient 5 checkup completed

Doctor taking Rest..

patient 6 checkup completed

patient 7 checkup completed

 

 

RegularPython

This website helps to learn ptyhon from basics to advanced level. Everything explained with some practical examples.

  • About
  • Privacy
  • Video Courses
  • Online Test
  • Python Blog

Marthahalli, Bengalore.
regularpython@gmail.com

© Copyright 2020 RegularPython.

  • Sign-in
  • Sign-up