Python While True Counter
I was recently trying to find a clean way of doing something like the following, except for a while True
loop
(without a known list_of_values
up front)
for i, value in enumerate(list_of_values):
do_something(i, value)
I was trying to paginate though an as yet unknown number of pages to be returned by an API
Something like this would work, but it seemed too verbose (3 lines to achieve my goal):
page = 1 # 1
all_page_data = []
while True: # 2
page_data = get_page_data(page=page)
all_page_data.extend(page_data)
if page_data == []:
break
page += 1 # 3
I ended up finding a nice alternative in the standard library itertools, which felt a bit cleaner (1 line, ignoring import)
import itertools
all_page_data = []
for page in itertools.count(start=1): # 1
page_data = get_page_data(page=page)
all_page_data.extend(page_data)
if page_data == []:
break
Cleaning up to just the important info:
import itertools
for i in itertools.count(start=1):
do_something(i)
if condition:
break