Program - Generators are faster than list comprehension


Topic: Program - Generators are faster than list comprehension

Solution

import timeit
def test_plainlist(plain_list):
    for i in plain_list():
        pass
def test_listcompr(listcompr):
    for i in listcompr():
        pass
def test_generator(generator):
    for i in generator():
        pass
def test_generator_yield(generator_yield):
    for i in generator_yield():
        pass
print('plain_list:     ', end='')
%timeit test_plainlist(plainlist)
print('\nlistcompr:     ', end='')
%timeit test_listcompr(listcompr)
print('\ngenerator:     ', end='')
%timeit test_generator(generator)
print('\ngenerator_yield:     ', end='')
%timeit test_generator_yield(generator_yield)



List all Python Programs