python - Get index of recently appended item -
is there straightforward way index of item appended list? need keep track of last added item.
i came 2 possible solutions:
# workaround 1 # last added 1 @ 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 @ index 0 know index of last added >> li = ['a', 'b', 'c',] >> li.insert(0, 'd') >> last_item = li[0]
is there trick index of appended item?
if there's not, of above use , why? different workaround suggest?
li[-1]
last item in list, , hence 1 appended end:
>>> li = [1, 2, 3] >>> li.append(4) >>> li[-1] 4
if need index, not item, len(li) - 1
fine, , efficient (since len(li)
computed in constant time - see below)
in source of cpython, len
lists mapped function list_length
in objects/listobject.c
:
static py_ssize_t list_length(pylistobject *a) { return py_size(a); }
py_size
macro accessing size attribute of python objects, defined in include/object.h
:
#define py_size(ob) (((pyvarobject*)(ob))->ob_size)
hence, len(lst)
single pointer dereference.
Comments
Post a Comment