pythonic way to iterate over part of a list
You can try itertools.islice(iterable[, start], stop[, step])
:
import itertools
for line in itertools.islice(list , start, stop):
foo(line)
The original solution is, in most cases, the appropriate one.
for line in lines[2:]:
foo(line)
While this does copy the list, it is only a shallow copy, and is quite quick. Don't worry about optimizing until you have profiled the code and found this to be a bottleneck.
Although itertools.islice
appears to be the optimal solution for this problem, somehow, the extra import just seems like overkill for something so simple.
Personally, I find the enumerate
solution perfectly readable and succinct - although I would prefer to write it like this:
for index, line in enumerate(lines):
if index >= 2:
foo(line)
You might build a helper generator:
def rangeit(lst, rng):
for i in rng:
yield lst[i]
for e in rangeit(["A","B","C","D","E","F"], range(2,4)):
print(e)