Is there a pythonic way of knowing when the first and last loop in a for is being passed through?
I don't know of anything built-in, but you can easily write a generator to give you the required information:
def firstlast(seq):
seq = iter(seq)
el = prev = next(seq)
is_first = True
for el in seq:
yield prev, is_first, False
is_first = False
prev = el
yield el, is_first, True
>>> list(firstlast(range(4)))
[(0, True, False), (1, False, False), (2, False, False), (3, False, True)]
>>> list(firstlast(range(0)))
[]
>>> list(firstlast(range(1)))
[(0, True, True)]
>>> list(firstlast(range(2)))
[(0, True, False), (1, False, True)]
>>> for count, is_first, is_last in firstlast(range(3)):
print(count, "first!" if is_first else "", "last!" if is_last else "")
0 first!
1
2 last!
You could use enumerate
and compare the counter with the length of the list:
for i, form_data in enumerate(step.hashes):
if i < len(step.hashes):
whatever()
for form_data in step.hashes[:-1]:
# get and fill the current form with data in form_data
for form_data in step.hashes[-1:]:
# get and fill the current form with data in form_data
# click the button that enables the next form
# submit all filled forms
Don't like the repetition of get and fill the current form with data in form_data
? Define a function.