Daniil Kolesnichenko2015-05-16 22:34:18
Daniil Kolesnichenko, 2015-05-16 22:34:18

Why do we need infinite Python arrays?

I don't really understand the meaning of infinite arrays in Python. It would be nice if you could just refer to a specific element, and it would be calculated, and the result would be automatically cached and all that. So no, after all, you need to iterate over the elements with a for-in loop. It is not clear whether there is any profit from this compared to a function that returns the desired element instead of an infinite array?

def factorial():
    i = 1
    k = 1
    while True:
        yield k
        k = k * i
        i += 1

factorial()[5] # так нельзя

for i in factorial():
    if ...: break # так можно, но зачем?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Valery Khizhevsky, 2018-06-14

vertical-align: middle

Oleg Dobrygin, 2018-06-14

Like this: https://jsfiddle.net/tg1pvsoz/1/

Vladimir Abramov, 2015-05-16

It's not an array, it's a generator. Its similarity with an array is only that both are iterable.
Why generators are needed is perfectly explained with examples here www.diveintopython3.net/generators.html

bobrovskyserg, 2015-05-16

The array (list) is a full barrel (of water).
A generator is a pipe from which water flows.
A barrel will not always replace a pipe.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question