简体   繁体   中英

Pythonic way to get last index value of enumerate

When I enumerate through a list, is there an intended, pythonic way of obtaining the last index value provided?

Something that would get the equivalent of this:

highest = None
for index, value in enumerate(long_list):
    # do stuff with index and value
    highest = index
return highest

This approach I don't like. It has hundreds of unnecessary variable assignments. Also, it's ugly.

Background: I have an ordered list build with a RDBS and SQLAlchemy, using numbers as indexes in the relation table. Also I store the highest used index number in the list table, for easy appending of new entries (without extra max lookup on relation table). For when things get messed up, for whatever reason, I included a reorg function, that rebuilds indexes starting from 0 (to remove any gaps). I to that by for-enumerate-iterating over the association table. After that I need to count them or max the index, to get my new highest index value for the list table. That kinda bugs me.

Suggestions? Preferably something that works in 2.7.

To get the last index of a list

len(mylist)-1

To get the last element of a list you can simply use a negative index.

mylist[-1]

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