in Technology by
What are generators in Python?

1 Answer

0 votes
by

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.
Let's try and build a generator for fibonacci numbers -

## generate fibonacci numbers upto n
def fib(n):
    p, q = 0, 1
    while(p < n):
        yield p
        p, q = q, p + q

x = fib(10)    # create generator object 
  
## iterating using __next__(), for Python2, use next()
x.__next__()    # output => 0
x.__next__()    # output => 1
x.__next__()    # output => 1
x.__next__()    # output => 2
x.__next__()    # output => 3
x.__next__()    # output => 5
x.__next__()    # output => 8
x.__next__()    # error
  
## iterating using loop
for i in <strong style="-webkit-font-smoothing:subpixel-antialiased; border:

Related questions

0 votes
    This question already has answers here: asynchronous python itertools chain multiple generators (2 answers) Closed 2 ... for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Jun 3, 2022 in Education by JackTerrance
0 votes
    Why Syn. Generators Are Used For The Production Of Electricity?...
asked Dec 12, 2020 in Technology by JackTerrance
0 votes
    Mention what does path generators include in d3.js?...
asked Nov 14, 2020 in Technology by JackTerrance
0 votes
    What are the values of the following Python expressions? 2**(3**2) (2**3)**2 2**3**2 a) 512, 64, 512 b) 512, 512, 512 c) 64, 512, 64 d) 64, 64, 64...
asked Dec 31, 2022 in Technology by JackTerrance
0 votes
    What are builtin Data Types in Python?...
asked Aug 20, 2021 in Technology by JackTerrance
0 votes
    What are the supported data types in Python?...
asked Apr 24, 2021 in Technology by JackTerrance
0 votes
    What are the Difference between staticmethod and classmethod in Python?...
asked Jan 9, 2021 in Technology by JackTerrance
0 votes
    What are metaclasses in Python?...
asked Jan 9, 2021 in Technology by JackTerrance
0 votes
0 votes
    How are arguments passed by value or by reference in python?...
asked Dec 7, 2020 in Technology by JackTerrance
0 votes
0 votes
    What are global, protected and private attributes in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
0 votes
    What are modules and packages in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
0 votes
    What are the common built-in data types in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
0 votes
    What are decorators in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
...