Main Content

Last elements in a Perl or Python list

Archive - Originally posted on "The Horse's Mouth" - 2007-08-16 10:45:30 - Graham Ellis

How do we refer to the elements of a list? By index number, starting at zero and stopping one short of the number of elements in the list. So a 20 element list has element numbers 0 to 19.

How can we refer to the last element, then? We could write an expression based on the length of the list - so
mylist[len(mylist)-1] in Python
$mylist[@mylist-1] or $mylist[$#mylist] in Perl.
That's going to get very messy if you want to do a lot of work on the end elements of a list, so (in both Perl and Python), you can refer to members of a list by a negative position number, meaning "number of positions from the end".

So:
mylist[-1] - last element of a list in Python
$mylist[-2] - next to last (penultimate) element of a list in Perl