简体   繁体   中英

Accessing the last element in a list in Python

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

list_a[-1]是访问最后一个元素的方法

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

Tested on Python 2.7.3

This solution will work for any sized list.

list_a = [0,1,3,1]

^ We define list_a

last = (len(list_a) - 1)

^We count the number of elements in the list and subtract 1. This is the coordinate of the last element.

print "The last variable in this list is", list_a[last]

^We display the information.

a = [1, 2, 3, 4, 1, 'not a number']
index_of_last_number = 0

for index, item in enumerate(a):
    if type(item) == type(2):
        index_of_last_number = index

The output is 4, the index in array a of the last integer. If you want to include types other than integers, you can change the type(2) to type(2.2) or something.

To be absolutely sure you find the last instance of "1" you have to look at all the items in the list. There is a possibility that the last "1" will not be the last item in the list. So, you have to look through the list, and remember the index of the last one found, then you can use this index.

list_a = [2, 1, 3, 4, 1, 5, 6]

lastIndex = 0

for index, item in enumerate(list_a):
    if item == 1:
        lastIndex = index

print lastIndex

output:

4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM