Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does range have to calculate all previous values when using a index

In python 3, range supports indexing but I am wondering exactly how that works.

For example: range(100000000000000000000000000)[-1]

I have a basic understanding that the range function actually returns a range object that takes up a limited amount of memory. Does that mean that to get to the last value, it has to calculate all the previous values?

like image 874
PaulC Avatar asked Oct 21 '13 12:10

PaulC


People also ask

Does INDEX match return the first value?

When there is a matching color, MATCH returns the position first TRUE found. This value is fed into the INDEX function as the row number, with the named range "things" provided as the array. When there is at least one match, INDEX returns the color at that position.

How do you INDEX a range in Excel?

To fetch a certain item from the list, you just write =INDEX(range, n) where range is a range of cells or a named range, and n is the position of the item you want to get.

Which function is used to find the INDEX of a specific value in a range?

The Excel INDEX function returns the value at a given location in a range or array. You can use INDEX to retrieve individual values, or entire rows and columns. The MATCH function is often used together with INDEX to provide row and column numbers.


1 Answers

It is not required to get previous value to get the last value.

It is computed by compute_item function (which is called by compute_range_item <- range_item ...).

From Python 3.3 source code (Objects/rangeobjects.c)

static PyObject *
compute_item(rangeobject *r, PyObject *i)
{
    PyObject *incr, *result;
    /* PyLong equivalent to:
     *    return r->start + (i * r->step)
     */
    incr = PyNumber_Multiply(i, r->step);
    if (!incr)
        return NULL;
    result = PyNumber_Add(r->start, incr);
    Py_DECREF(incr);
    return result;
}
like image 77
falsetru Avatar answered Sep 30 '22 19:09

falsetru