Difference between Iterator and Generator in Python

In this article, we’ll mainly learn about the difference between iterator and generator in Python, but of course, we need to know them separately as well.

Let’s start!!!!

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is Python Generators

A python generator’s typical function lends coder a sequence of values to iterate on.

The following is a general example of generators in python.

Python Generator Example

a=(1,2,3,4,5,6,7,8,9,10,11)
for i in range(1,10,2):
    print(i)
   

Output:

1
3
5
7
9

Creating Generators in Python

It is quite simple to create a generator in Python in runtime. If a function contains an output statement then the generator needs to work as a library. Both yield and Return will return some value from a function from a particular code.

Python Generators with a Loop Example

def thisistech(string):
    tech = len(string)
    for k in range(tech - 1, -1, -1):
        yield string[k]

for char in thisistech("whassup"):
    print(char)

Output:

p
u
s
s
a
h
w

Python Generator Expression

Simple python generator can be easily created by importing from the library directly.

Python generator Expression Example

myfirstlist = [1, 10,9,0]

listmy = [k**2 for k in myfirstlist]

generator = (k**2 for k in myfirstlist)

print(listmy)
print(generator)

Output:

[1, 100,81,0]

Code:

mysecondlist = [1, 10]

p = (j**2 for j in mysecondlist)
print(next(p))

Output:

1

Generator expressions can be used as function arguments in any code, as:

Syntax:

>>> sum(w**2 for x in mysecondlist)

Advantages of Python Generators

1. Easy to Implement Anywhere
The python generators are easy to implement in the dynamic as well as user-defined codes. They generally fetch values from libraries, which make them accessible on every python version.

2. Highly Memory Efficient
A normal function to return a sequence will create the entire sequence in memory before returning the result within the runtime itself.

3. Represent Infinite Stream
Generators can represent the length of a series of infinite numbers taken at a time. And this is supported by the library function.

4. Pipelining Generators in Python
Multiple generators can be used to pipeline a series of operations within the runtime itself.

Advanced Generators

These generators work on the yielding property of the libraries. They are basically used in data and csv files.

Python Iterators

A Python iterator typically returns us an iterator object- one value at a time. An example of an iterator in python.

Example of Python iterators

>>> next(it)

Output:

Traceback (most recent call last)

Iterables in Python

As the name suggests, the iterables are those defined objects which can iterate different values for a code.

They are generally in the form of arrays.

it[Symboloftheiterator] = function* () 
  yield 2;
  yield 1;

Comparison Between Python Generator and Iterator

S.no  Parameters Generator Iterator
1 Implementation  Implemented using a function defined in the runtime. Implemented using a class in the code.
2 Yield usage for coder Generator uses the ‘yield’ keyword Iterator does not use any keyword
3 Class variable Generator does not need a class in python. Iterator implements its own class
4 Globals and locals  Generator saves the states of the local variables Iterator also does not uses local variable
5 Yield usage for user Uses the yield keyword for the output. Does not use the yield keyword anywhere in the code.
6 Efficiency  Generators  write fast and compact code Iterator writes custom and long codes
7 Functions Generator use python functions Iterator,use the iter() and next() functions
8 Storage capacity Generator is not memory efficient Iterator is memory-efficient
9 Relative working Usage results in a concise code in any  relative function. Usage results in a relatively less concise code as compared in the whole python code.

Code:

def thisisnew():
#this defines new variable
if i==1:
   While i>0:
      Yield i
 i-=1
#this executes only when first is not satisfied
For i in thisistech():
    print(i)
For i in thisisnew():
    print()

Output:

error

A generator function class can be identified in a python code.

Code:

def thisisgen():
    print("class is a generator")

Output:

>>> thisisgen()
class is a generator
>>>

Common Relationship Between Python Iterators and Generators

A python iterator and generator both fetch information from the predefined libraries. They help in the proper conduct of the code.

Code:

def thisistech():
    print("this is true")

Output:

>>> thisistech()
this is true
>>>

Conclusion

Having learnt Generators vs Iterators in Python, now we know that coders can easily interpret and manipulate these two, but this is only possible with practice.

We also learnt how a coder can easily use generators to make code more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.