Get index of recently appended item

2020-03-01 08:12发布

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?

标签: python list
3条回答
家丑人穷心不美
2楼-- · 2020-03-01 08:51

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).

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-03-01 09:08

A third possible solution would be to subclass list and override the append method, so that it automatically stores in a property like mylist.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 of mylist[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 or yield, for example).

查看更多
Lonely孤独者°
4楼-- · 2020-03-01 09:17

li[-1] is the last item in the list, and hence the one that was most recently appended to its end:

>>> li = [1, 2, 3]
>>> li.append(4)
>>> li[-1]
4

If you need the index, not the item, then len(li) - 1 is just fine, and very efficient (since len(li) is computed in constant time - see below)


In the source of CPython, len for lists is mapped to function list_length in Objects/listobject.c:

static Py_ssize_t
list_length(PyListObject *a)
{
    return Py_SIZE(a);
}

Py_SIZE is just a macro for accessing the size attribute of all Python objects, defined in Include/object.h:

#define Py_SIZE(ob)     (((PyVarObject*)(ob))->ob_size)

Hence, len(lst) is essentially a single pointer dereference.

查看更多
登录 后发表回答