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

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

If your sequence isn't terribly long then you can just slice it:

for val in array[:-1]:
  do_something(val)
else:
  do_something_else(array[-1])

Solution 3 - Python

using itertools

>>> from itertools import repeat, chain,izip
>>> for val,special in izip(array, chain(repeat(False,len(array)-1),[True])):
...     print val, special
... 
1 False
2 False
3 False
4 False
5 True

Version of liori's answer to work on any iterable (doesn't require len() or slicing)

def last_flagged(seq):
    seq = iter(seq)
    a = next(seq)
    for b in seq:
        yield a, False
        a = b
    yield a, True        

mylist = [1,2,3,4,5]
for item,is_last in last_flagged(mylist):
    if is_last:
        print "Last: ", item
    else:
        print "Not last: ", item

Solution 4 - Python

If your logic is never breaking out of the loop then a for...else construct might work:

In [1]: count = 0
   ...: for i in [1, 2, 3]:
   ...:     count +=1
   ...:     print("any item:", i)
   ...: else:
   ...:     if count:
   ...:         print("last item: ", i)
   ...:
any item: 1
any item: 2
any item: 3
last item:  3

You need the count variable just in case the iterable is empty, otherwise the variable i won't be defined.

Solution 5 - Python

Simple way with an if condition:

for item in list:
    print "Not last: ", item
    if list.index(item) == len(list)-1:
        print "Last: ", item

Solution 6 - Python

for i in items:
  if i == items[-1]:
    print 'The last item is: '+i

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprosseekView Question on Stackoverflow
Solution 1 - PythonlioriView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PythonJohn La RooyView Answer on Stackoverflow
Solution 4 - PythonPedro M DuarteView Answer on Stackoverflow
Solution 5 - PythonMax DyView Answer on Stackoverflow
Solution 6 - Pythonahmad88meView Answer on Stackoverflow