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
Advertisement
Answer
JavaScript
x
4
1
for item in list[:-1]:
2
print "Not last: ", item
3
print "Last: ", list[-1]
4
If you don’t want to make a copy of list, you can make a simple generator:
JavaScript
1
16
16
1
# itr is short for "iterable" and can be any sequence, iterator, or generator
2
3
def notlast(itr):
4
itr = iter(itr) # ensure we have an iterator
5
prev = itr.next()
6
for item in itr:
7
yield prev
8
prev = item
9
10
# lst is short for "list" and does not shadow the built-in list()
11
# 'L' is also commonly used for a random list name
12
lst = range(4)
13
for x in notlast(lst):
14
print "Not last: ", x
15
print "Last: ", lst[-1]
16
Another definition for notlast:
JavaScript
1
3
1
import itertools
2
notlast = lambda lst:itertools.islice(lst, 0, len(lst)-1)
3