Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat the last element in list differently in Python?

Tags:

python

I need to do some special operation for the last element in a list. Is there any better way than this?

 array = [1,2,3,4,5]  for i, val in enumerate(array):    if (i+1) == len(array):      // Process for the last element    else:      // Process for the other element  
like image 353
prosseek Avatar asked Mar 11 '10 22:03

prosseek


People also ask

How do you change the last element of a list in Python?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

How do I extract the last element of a list?

Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.

How do you print the last two elements of a list in Python?

Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.


1 Answers

for item in list[:-1]:     print "Not last: ", item print "Last: ", list[-1] 

If you don't want to make a copy of list, you can make a simple generator:

# itr is short for "iterable" and can be any sequence, iterator, or generator  def notlast(itr):     itr = iter(itr)  # ensure we have an iterator     prev = itr.next()     for item in itr:         yield prev         prev = item  # lst is short for "list" and does not shadow the built-in list() # 'L' is also commonly used for a random list name lst = range(4) for x in notlast(lst):     print "Not last: ", x print "Last: ", lst[-1] 

Another definition for notlast:

import itertools notlast = lambda lst:itertools.islice(lst, 0, len(lst)-1) 
like image 122
liori Avatar answered Sep 20 '22 16:09

liori