[Python] How can I check if I can fetch data from an iterable object several times?

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

  1. Stack

    Stack Membro Participativo

    Simple method which prints elements from some source two times:

    def p2(source):
    for x in source:
    print(x)
    for x in source:
    print(x)


    This method works as expected if the source is a list. But if the source is an iterator or generator this would not work.

    >>> p2(x*x for x in [1, 2, 3])
    1
    4
    9


    The second for loop would try to fetch data from the already exhausted generator and would not fetch any items from it.

    Of course, to fix this problem I can first fetch all the elements from the source into a list and then print elements from this list:

    def p2_v2(source):
    local_storage = [x for x in source]
    for x in local_storage:
    print(x)
    for x in local_storage:
    print(x)


    But in case the source argument is already a list creation of an additional list looks like an unnecessary overhead.

    How can I check if I can fetch objects from the source several times?

    Continue reading...

Compartilhe esta Página