user3124200
user3124200

Reputation: 353

Using a variable before it’s been defined

Why does the code below work when pop_zero and pop_end use the list variable, x, before x has even been defined (x = list(range(i))). In other words pop_zero and pop_end are defined in terms of x, but x is defined after pop_zero and pop_end. Why isn’t this a problem?

import timeit
from timeit import Timer
pop_zero = Timer("x.pop(0)", "from __main__ import x")
pop_end = Timer("x.pop()", "from __main__ import x")
print("pop(0) pop()")
for i in range(1000000,100000001,1000000):
    x = list(range(i))
    pt = pop_end.timeit(number=1000)
    x = list(range(i))
    pz = pop_zero.timeit(number=1000)
    print("%15.5f, %15.5f" %(pz,pt))

Upvotes: 2

Views: 89

Answers (1)

iz_
iz_

Reputation: 16603

When you create a Timer object, it doesn't actually execute the code inside yet. Only when you call one of its method (i.e. .timeit()) does it actually run the code.

Upvotes: 1

Related Questions