Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check first and last index of a list

Tags:

python

list

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

like image 315
Hellnar Avatar asked Aug 03 '10 08:08

Hellnar


3 Answers

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 ;)

like image 55
Felix Kling Avatar answered Nov 15 '22 23:11

Felix Kling


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
like image 20
Autoplectic Avatar answered Nov 16 '22 00:11

Autoplectic


for index, obj in enumerate(object_list):
    do_something
    if index == 0:
        do_something_else
    if index == len(object_list)-1:
        do_another_thing
like image 3
Amber Avatar answered Nov 16 '22 00:11

Amber