3

To support indexing over a collection Python includes enumerate() function. It provides index over collection.

for index, item in enumerate(list):
    # do domething
    print index

In my case I have a huge list and wonder if it is faster to create index manually that use enumerate()? e.g.

index = 0
for item in list:
    # do something
    print index
    index = index + 1
Gunnar Schigel
  • 266
  • 4
  • 10
  • 2
    how could enumerate be slower than that? That is essentially its implementation, so why would a built-in be slower? You've even linked to the PEP which gives that naive implementation. – David Heffernan Mar 16 '11 at 23:39

2 Answers2

5

The enumerate function is built in; it does not count the elements a priori. The following is the C-code implementation:

static PyObject *
enum_next(enumobject *en)
{
    PyObject *next_index;
    PyObject *next_item;
    PyObject *result = en->en_result;
    PyObject *it = en->en_sit;

    next_item = (*it->ob_type->tp_iternext)(it);
    if (next_item == NULL)
        return NULL;

    next_index = PyInt_FromLong(en->en_index);
    if (next_index == NULL) {
        Py_DECREF(next_item);
        return NULL;
    }
    en->en_index++; 

    if (result->ob_refcnt == 1) {
        Py_INCREF(result);
        Py_DECREF(PyTuple_GET_ITEM(result, 0));
        Py_DECREF(PyTuple_GET_ITEM(result, 1));
    } else {
        result = PyTuple_New(2);
        if (result == NULL) {
            Py_DECREF(next_index);
            Py_DECREF(next_item);
            return NULL;
        }
    }
    PyTuple_SET_ITEM(result, 0, next_index);
    PyTuple_SET_ITEM(result, 1, next_item);
    return result;
}

So, the function yields a next en integer on the fly.

Escualo
  • 40,844
  • 23
  • 87
  • 135
1

No, enumerate() isn't making a decorated copy of your list. It takes a something like an iterator as its argument and returns something like an iterator as its result, so it's doing more or less what your "manual" example is doing.

rmalouf
  • 3,353
  • 1
  • 15
  • 10