Is there a straightforward way to get the index of an item I just appended to a list? I need to keep track of the last added item.
I came up with two possible solutions:
# Workaround 1
# The last added is the one at index len(li) - 1
>> li = ['a', 'b', 'c',]
>> li.append('d')
>> last_index = len(li) - 1
>> last_item = li[len(li) - 1]
# Workaround 2
# Use of insert at index 0 so I know index of last added
>> li = ['a', 'b', 'c',]
>> li.insert(0, 'd')
>> last_item = li[0]
Is there a trick to get the index of an appended item?
If there's not, which of the above would you use and why? Any different workaround you suggest?
You can index lists from either side. The index of the last element is always -1, you don't need to call
len
. Repeatedly inserting at the beginning is very inefficient (requires all elements in the list to be moved one place down).A third possible solution would be to subclass
list
and override theappend
method, so that it automatically stores in a property likemylist.last_added
whenever you call it.This approach - if extended to other list methods - offers the advantage that you could potentially create a class where it will keep track of the index of the last added element regardless of the method used (
insert
,append
, or simple assignment ofmylist[some_index] = some_value
).Another advantage of embedding this info in the list object is that you will pass around it without having to worry about namespaces (so you will be able to retrieve it even if your list is passed by a
return
oryield
, for example).li[-1]
is the last item in the list, and hence the one that was most recently appended to its end:If you need the index, not the item, then
len(li) - 1
is just fine, and very efficient (sincelen(li)
is computed in constant time - see below)In the source of CPython,
len
for lists is mapped to functionlist_length
inObjects/listobject.c
:Py_SIZE
is just a macro for accessing the size attribute of all Python objects, defined inInclude/object.h
:Hence,
len(lst)
is essentially a single pointer dereference.