[Python] how generators work in python

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am novice in Python and programming. Generators are a bit too complicated to understand for new programmers. Here's my theory on generator functions in Python:


    1. Any function contains a yield statement will return a generator object


    2. A generator object is a stack contains state


    3. Each time I call .next method Python extracts the function's state and when it finds another yield statement it'll bind the state again and deletes the prior state:

    Example:

    [
    [state1] # Stack contains states and states contain info about the function
    [state2] # State1 will be deleted when python finds the other yield?
    ]


    This is of course might be like the stupidest theory on earth, but forgive me I am just new in the coding word.

    My Questions:


    1. What Python internally makes to store the states ?


    2. Does yield statement adds a state to a stack if it exists ?


    3. What yield creates internally ? I understand yield creates a generator object, however, I wonder what generator objects contain that makes them work ? are they just a stack/list of states and we you use .next method to extract each state and Python will call the function with the indexed state automatically for instance ?

    Continue reading...

Compartilhe esta Página