lundi 21 mai 2018

Python Generator - Function unintendedly returning a generator [duplicate]

This question already has an answer here:

This function is a test function made for the purpose of understanding another problem I'm having in some other code. I am trying to figure out why a generator is being returned in the case where the list comprehension code should execute rather than the generator code.

def test(a, gen=False):

    if not gen:
        return [x for x in range(a)]
    else:
        for i in range(a):
            yield i


print(test(10))
print(test(10, gen=True))



<generator object test at 0x7f20882a0bf8>
<generator object test at 0x7f20882a0bf8>

Aucun commentaire:

Enregistrer un commentaire