Assuming I have object_list list which contains objects.
I want to check if my current iteration is is at the first or the last.
for object in object_list:
do_something
if first_indexed_element:
do_something_else
if last_indexed_element:
do_another_thing
How can this be achieved? I know that I can use range and count index but if feels clumsy.
Regards
You can use enumerate()
:
for i, obj in enumerate(object_list):
do_something
if i == 0:
do_something_else
if i == len(object_list) - 1:
do_another_thing
But instead of checking in every iteration which object you are dealing with, maybe something like this is better:
def do_with_list(object_list):
for obj in object_list:
do_something(obj)
do_something_else(object_list[0])
do_another_thing(object_list[-1])
Imagine you have a list of 100 objects, then you make 198 unnecessary comparisons, because the current element cannot be the first or last element in the list.
But it depends on whether the statements have to be executed in a certain order and what they are doing.
Btw. don't shadow object
, it is already an identifier in Python ;)
li = iter(object_list)
obj = next(li)
do_first_thing_with(obj)
while True:
try:
do_something_with(obj)
obj = next(li)
except StopIteration:
do_final_thing_with(obj)
break
for index, obj in enumerate(object_list):
do_something
if index == 0:
do_something_else
if index == len(object_list)-1:
do_another_thing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With