Iterate through Python list and do something on last element -



Iterate through Python list and do something on last element -

i'm looking pythonic way iterate through list , on lastly (and last) element. there 2 ways can see this, of guess sec best:

for item in a_list: #do every element if a_list.index(item) == len(a_list) - 1: # lastly 1

and

for n, item in enumerate(a_list): #do every element if n == len(a_list) - 1 : # lastly 1

however, wonder if there way of doing without calling len() on list i'm iterating over. i'm quite happy, way, told isn't should worry about.

for item in lst: do_something_to(item) else: do_something_extra_special_to_last(item)

here assume want lastly item (the normal action still taken on beforehand). assume aren't hitting break statements (in case else won't execute). of course, don't need else:

for item in lst: do_something_to(item) do_something_extra_special_to_last(item)

should work since loop variable "leaks" enclosing scope , if there breaks you're worried , looping on sequence, why not:

for item in lst: do_something_to(item) do_something_extra_special_to_last(lst[-1])

python

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -