开发者

Python check first and last index of a list

开发者 https://www.devze.com 2023-01-10 04:28 出处:网络
Assuming I have object_l开发者_开发技巧ist list which contains objects. I want to check if my current iteration is is at the first or the last.

Assuming I have object_l开发者_开发技巧ist 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


first = True
for o in object_list:
    do_something(o)
    if first:
        first = False
        do_something_with_first(o)
if 'o' in locals():
    do_something_with_last(o)


You just have to use a counter, no need for range :

Let's say your counter is cpt.

if cpt == 0:
  print "first"

if cpt == len(object_list) - 1:
  print "last"

edit : the enumerate solution may be more elegant.


  1. You can make i = 0 and then i++ in iterations. So if i==0 it is first iteration, if i == list.size()-1 than it is last iteration.
  2. There must be smth like indexOf(object), which returns position of element in list. if 0 - than first iteration, if size()-1 than last. But it is expensive.
  3. use enumerate. See Amber or Felix posts.
  4. compare current element to list[0] and to list[-1]. in first case - first iteration, in last case - last iteration. It is expensive too.

So i'd choose 1 or 3.
PS: list.size() is len(list) of course.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号