Accessing the last element in a list in Python

python

Solution

You can use enumerate to iterate through both the items in the list, and the indices of those items.

for idx, item in enumerate(list_a):
    if idx == len(list_a) - 1:
        print item, "is the last"
    else:
        print item, "is not the last"

Result:

0 is not the last
1 is not the last
3 is not the last
1 is the last

Problem

I have a list for example: list_a = [0,1,3,1] and I am trying to iterate through each number this loop, and if it hits the last "1" in the list, print "this is the last number in the list" since there are two 1's, what is a way to access the last 1 in the list? I tried: ``` if list_a[-1] == 1: print "this is the last" else: # not the last ``` This does not work since the second element is also a 1. Tried: ``` if list_a.index(3) == list_a[i] is True: print "this is the last" ``` also did not work, since there are two 1's

Original source