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?