kratenko
kratenko

Reputation: 7592

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.

Upvotes: 2

Views: 10829

Answers (2)

Alex Che
Alex Che

Reputation: 7112

You can just access the index variable after the loop. No need to introduce another variable (highest in your case).

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

Upvotes: 1

Jay
Jay

Reputation: 2686

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]

Upvotes: 6

Related Questions