Python syntax: using loops inside a timeit statement

python, timeit

Solution

Your failing statement is syntactically incorrect. If you need to time multiple statement's define it in a function and call Timer, after importing the function from main

>>> def foo():
    n = []
    for i in xrange(10): n.append(oct(i))    

>>> Timer("foo()","from __main__ import foo")

Now you need to understand why the failing statement is incorrect

Excerpt from the docs for Compound Statement

A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines.

stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

and similarly, a simple statement is

simple_stmt ::=  expression_stmt
                 | assert_stmt
                 | assignment_stmt
                 | augmented_assignment_stmt
                 | pass_stmt
                 | del_stmt
                 | print_stmt
                 | return_stmt
                 | yield_stmt
                 | raise_stmt
                 | break_stmt
                 | continue_stmt
                 | import_stmt
                 | global_stmt
                 | exec_stmt

It should now be clear to you when a semi-colon can (not should) be used.

Problem

Two of these statements run while the other fails with a syntax error. What am I doing wrong? ``` >>> Timer('for i in xrange(10): oct(i)').repeat(3) [2.7091379165649414, 2.6934919357299805, 2.689150094985962] >>> Timer('n = [] ; n = [oct(i) for i in xrange(10)]').repeat(3) [4.0500171184539795, 3.6979520320892334, 3.701982021331787] >>> Timer('n = [] ; for i in xrange(10): n.append(oct(i))').repeat(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/timeit.py", line 136, in __init__ code = compile(src, dummy_src_name, "exec") File "<timeit-src>", line 6 n = [] ; for i in xrange(10): n.append(oct(i)) ^ SyntaxError: invalid syntax ```

Original source