0

Suppose that I have the list list_1 and that I want to iterate over its elements from indices i to (j - 1), where j > i.

My options, as I know them are:

Option 1: Constructing a whole new list

for element in list_1[i:j]:
    # do something

Option 2: Iterating over the indices themselves

for index in range(i, j):
    element = list_1[index]
    # do something

Both options are not desirable. The first option is not desirable because it involves construction of a new list. The second option is not desirable especially in terms of readability, as its iteration is over the indices, rather than over the list elements.

Is there a built-in generator function that iterates over the elements in a given range?

jpp
  • 159,742
  • 34
  • 281
  • 339
SomethingSomething
  • 11,491
  • 17
  • 68
  • 126

1 Answers1

4

You can use itertools.islice() to iterate over a subset of values, by index:

from itertools import islice

for element in islice(list_1, i, j):

This will still iterate over all i - 1 initial values of list_1, but will do so in C and not keep skipped values in memory.

Demo:

>>> from itertools import islice
>>> list_1 = [42, 81, 117, 3103, 17, 22]
>>> for elem in islice(list_1, 2, 5):
...     print(elem)
...
117
3103
17
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks you. This looks just liked what I hoped to have. – SomethingSomething Oct 09 '18 at 13:19
  • This `itertools` module seems to be something a Python programmer must learn and master. It is a shame that I don't regularly use it. Is there a usage convention? Is it more common to use `from itertools import ` rather than `import itertools as it` and then use `it.()` ? – SomethingSomething Oct 09 '18 at 13:40
  • 1
    @SomethingSomething: I use it like any other standard library module, I don't usually abbreviate module names. That practice is more usually found with datascience packages as they use these interactively in Jupyther notebooks and shorter names matter more. – Martijn Pieters Oct 09 '18 at 15:00