Difference between function and generator?

0 votes
What is the difference between normal functions and generator functions?
Jul 15, 2019 in Python by Fata
• 1,050 points
1,145 views

1 answer to this question.

0 votes

Normal Functions vs Generator Functions:

Generators in Python are created just like how you create normal functions using the ‘def’ keyword. But, Generator functions make use of the yield keyword instead of return. This is done to notify the interpreter that this is an iterator. Not just this, Generator functions are run when the next() function is called and not by their name as in case of normal functions. Consider the following example to understand it better:

EXAMPLE:

def func(a):

    yield a

a=[1,2,3]

b=func(a)

next(b)

OUTPUT: [1, 2, 3] 

As you can see, in the above output, func() is making use of the yield keyword and the next function for its execution. But, for normal function you will need the following piece of code:

EXAMPLE:

def func(a):

    return a

a=[1,2,3]

func(a)

OUTPUT: [1, 2, 3] 

answered Jul 15, 2019 by Wajiha
• 1,950 points

Related Questions In Python

0 votes
1 answer

Difference between a normal def defined function and lambda function in python?

Have a look at this code: # Python ...READ MORE

answered May 20, 2019 in Python by Trisha
1,090 views
0 votes
1 answer

What is the difference between map() and filter() function in python?

The map() function is a type of ...READ MORE

answered Jun 25 in Python by Sirajul
• 55,750 points
35 views
0 votes
1 answer

What's the difference in Qt between setVisible, setShown and show/hide

show() is just a convenience function for ...READ MORE

answered Apr 17, 2018 in Python by anonymous
2,999 views
0 votes
1 answer

What is the difference between list and tuple?

Lists are mutable(values can be changed) whereas ...READ MORE

answered May 4, 2018 in Python by aayushi
• 750 points
2,669 views
0 votes
1 answer

Generator Expressions vs. List Comprehension

Generator expression resemble list comprehensions. List comprehensions ...READ MORE

answered Jul 15, 2019 in Python by Wajiha
• 1,950 points
171 views
0 votes
1 answer

Generators with plots

Yes, you can. I tried doing it ...READ MORE

answered Jul 16, 2019 in Python by Wajiha
• 1,950 points
75 views
0 votes
0 answers

Produce infinite number stream?

Is it possible to produce an infinite ...READ MORE

Jul 16, 2019 by Fata
• 1,050 points
38 views
0 votes
1 answer

How to convert one list into generator?

Hi@akhtar, Say, you have one list A. Now convert ...READ MORE

answered Apr 23 in Python by MD
• 43,520 points
75 views
0 votes
1 answer

Difference between ElementTree and Minidom

Python allows parsing these XML documents using ...READ MORE

answered Jul 22, 2019 in Python by Wajiha
• 1,950 points
1,712 views
0 votes
1 answer

Difference between end and sep

end and sep are optional parameters of ...READ MORE

answered Jul 30, 2019 in Python by Wajiha
• 1,950 points
623 views