Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of recently appended item

Tags:

python

list

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?

like image 289
romeroqj Avatar asked Jul 01 '11 08:07

romeroqj


1 Answers

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.

like image 174
Eli Bendersky Avatar answered Sep 16 '22 12:09

Eli Bendersky