[Python] Shallow copying enumeration iterator behavior in Python

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to understand the behavior of iterators in Python, particularly when using the copy.copy() and copy.deepcopy() functions. I have the following script:

    import copy

    my_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

    def iterate_5_elements(iterator):
    for _ in range(5):
    print(next(iterator))

    my_iterator1 = enumerate(my_list)
    iterate_5_elements(my_iterator1)
    iterate_5_elements(my_iterator1)
    print("--------------------------------")

    my_iterator2 = enumerate(my_list)
    iterate_5_elements(copy.copy(my_iterator2))
    iterate_5_elements(copy.copy(my_iterator2))
    print("--------------------------------")

    my_iterator3 = enumerate(my_list)
    iterate_5_elements(copy.deepcopy(my_iterator3))
    iterate_5_elements(copy.deepcopy(my_iterator3))
    print("--------------------------------")


    And it produces this output:

    (0, 'a')
    (1, 'b')
    (2, 'c')
    (3, 'd')
    (4, 'e')
    (5, 'f')
    (6, 'g')
    (7, 'h')
    (8, 'i')
    (9, 'j')
    --------------------------------
    (0, 'a')
    (1, 'b')
    (2, 'c')
    (3, 'd')
    (4, 'e')
    (0, 'f')
    (1, 'g')
    (2, 'h')
    (3, 'i')
    (4, 'j')
    --------------------------------
    (0, 'a')
    (1, 'b')
    (2, 'c')
    (3, 'd')
    (4, 'e')
    (0, 'a')
    (1, 'b')
    (2, 'c')
    (3, 'd')
    (4, 'e')
    --------------------------------


    The first and third iterator behave as expected. However, with the second iterator (using copy.copy()), the output is strange: The letters continue from 'f' instead of starting from 'a' (expected behavior, its a shallow copy) but the numbers reset. Why does this happen? Why does the alphabet continues from 'f' after the first iteration, even though the index seems to reset?

    I was expecting the shallow copy to behave exactly like the first iterator, I.E. printing 0 through 9 and 'a' through 'f'

    Continue reading...

Compartilhe esta Página