1

I'm learning Python and this sqlite3 code is a bit align to me. Is Python going to optimize and run the SQL statement once?

for row in c.execute('SELECT * FROM stocks ORDER BY price'):
    print row
2
  • 1
    Yes, it will be run once. Does python create a new range every iteration in for i in range(100)..? Commented Apr 6, 2016 at 0:44
  • To be safe, why not assign the return of c.Execute(...) to a variable first, and then go into your loop: for row in stocksCollection: print row. That way there should be no doubt. Commented Apr 6, 2016 at 1:03

1 Answer 1

1

As I commented it will run once, the relevant part from the docs The for statement:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.

Emphasis mine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.