Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop in Python: Do stuff before first iteration

I want to optimize.

Simple solution

connection = get_db_connection()
for item in my_iterator:
    push_item_to_db(item, connection)

Drawback:

get_db_connection() is slow. If my_iterator is empty, then I want to avoid to call it.

"if None" solution

connection = None
for item in my_iterator:
    if connection is None:
        connection = get_db_connection()
    push_item_to_db(item, connection)

Drawback:

If there are 100k items in my_iterator, then if connection is None gets called 100k times (although it is needed only once). I want to avoid this.

Perfect solution ...

  1. don't call get_db_connection() if iterator is empty
  2. don't call if connection is None: uselessly for every iteration.

Any idea?

like image 774
guettli Avatar asked Apr 04 '16 10:04

guettli


People also ask

How do you skip the first iteration in a while loop?

you can simply put the 'quit' outside the while loop since the while loop will end when the url is the back to the first page again. You can add an init flag to not break the while loop when you are in it with the url for the first time.

Do Python for loops go in order?

Yes, it should, every time, since lists are ordered. If you are iterating over a dict , the order may be different than expected.

Does Python for loop start at 0 or 1?

Python for loop index start at 0 In Python by default, the range starts from 0 and ends at the value of the passed argument as -1. In this example, we do not iterate items through the list.

Do loops start at 1?

1. Most loops starts with 0.


1 Answers

You can do something like:

connection = None
for item in my_iterator:
    if connection is None:
        connection = get_db_connection()
    push_item_to_db(item, connection)

Simple solution. Don't need to overthink it. Even with 100k operations, x is None is just a reference comparison taking one Python opcode. You really don't need to optimise this compared to a full tcp roundtrip + disk write that happens on every insert.

like image 69
viraptor Avatar answered Sep 20 '22 12:09

viraptor