Solution 1
This works without a while True .
try: next(my_iterator) connection = get_db_connection() push_item_to_db(item, connection) except StopIteration: pass for item in my_iterator: push_item_to_db(item, connection)
Decision 2
If you know that this iterator never returns None (or any other unique object), you can use the default value next() :
if next(my_iterator, None) is not None: connection = get_db_connection() push_item_to_db(item, connection) for item in my_iterator: push_item_to_db(item, connection)
Decision 3
If you cannot guarantee a value that is not returned by the iterator, you can use the watch.
sentinel = object() if next(my_iterator, sentinel) is not sentinel: connection = get_db_connection() push_item_to_db(item, connection) for item in my_iterator: push_item_to_db(item, connection)
Decision 4
Using itertools.chain() :
from itertools import chain for first_item in my_iterator: connection = get_db_connection() for item in chain([first_item], my_iterator): push_item_to_db(item, connection)
source share