From what I know, we may use generator when we want to use the values only once. Using the 2 examples below, my logic is that the 2nd one should be faster, because the first one creates a list first and then loop over the values.. while the 2nd only process the values from the generator. Yet, when I calculate the time, the list comprehension is always faster then the generator. Why is this?
1st:
x = []
a = time.perf_counter()
for j in [i**2 for i in range(20000)]:
x.append(j)
print( time.perf_counter() - a )
2nd:
x = []
a = time.perf_counter()
for j in (i**2 for i in range(20000)):
x.append(j)
print( time.perf_counter() - a )