Introduction

Setup

Operators

variable

String

Number

Dtype & Comment

Lists

Tuples

Sets

Dictionaries

if else statement

For Loop

While Loop

iterator & iterable

Pre-Built functions

Function

Decorators

Generators

Types of errors

Exceptions Handling

OOP

Regular expression

Create module

OS module

Date module

Random module

Math

Statistics module

Exercise 1

Exercise 2

Exercise 3

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Python generator

What is generators in python?

Generators are sequence lists but generators are not iterable, although it is a sequence, like list or tuple or set.

In python how list save in a memory?

Suppose you have a list [1, 2, 3, 4, 5, 6, 7, 8, 9]. Now, this complete list will save in my memory at a time. In this case, it will take much time to create a list and after creating the list it will use much memory to save.

How generators save in memory?

In the case of generators, if we have 10 numbers then at first, the generator will generate only one number at a time. So when the second number comes, the first number will be removed or deleted and the second number will take place at that position. It means that first, it will generate the first number then after completing work with the first number, it will remove and delete the first number and generate the second number and this process will go on until it reaches the last number. So in generators, we will create a sequence like this.

When generators should be used?

If we want to use sequence values again and again then we use list or tuple, etc but when we want to use sequence values just for one time then we should use generators.

Example:1
Input
def genarator_func(n):
  for i in range(1,n+1):
    yield(i)
numbers=genarator_func(10)
for num in numbers:
  print(num)
Output
1
2
3
4
5
6
7
8
9
10

Here, by using the yield keyword we have created generators. To print generator values for loop is used.

Example:2
Input
def genarator_func(n):
  for i in range(1,n+1):
    if i%2==0:
      yield(i)
numbers=genarator_func(10)
for num in numbers:
  print(num)
Output
2
4
6
8
10

Generator comprehension

Syntax and rules are as same as list comprehension but in the list comprehension, we used the third bracket but in generator comprehension, we will use the first bracket.

Example:
Input
square=(i**2 for i in range(1,6))
for num in square:
  print(num)
Output
1
4
9
16
25

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.