Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pythonic way to iterate over part of a list

I want to iterate over everything in a list except the first few elements, e.g.:

for line in lines[2:]:     foo(line) 

This is concise, but copies the whole list, which is unnecessary. I could do:

del lines[0:2] for line in lines:     foo(line) 

But this modifies the list, which isn't always good.

I can do this:

for i in xrange(2, len(lines)):     line = lines[i]     foo(line) 

But, that's just gross.

Better might be this:

for i,line in enumerate(lines):     if i < 2: continue     foo(line) 

But it isn't quite as obvious as the very first example.

So: What's a way to do it that is as obvious as the first example, but doesn't copy the list unnecessarily?

like image 460
Claudiu Avatar asked Dec 29 '11 17:12

Claudiu


People also ask

How do you iterate through a specific range in Python?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

How do I get one part of a list in Python?

Using Python Slice Objects The general method format is: slice(start, stop, increment) , and it is analogous to start:stop:increment when applied to a list or tuple. That's it!


2 Answers

You can try itertools.islice(iterable[, start], stop[, step]):

import itertools for line in itertools.islice(list , start, stop):      foo(line) 
like image 112
soulcheck Avatar answered Sep 21 '22 11:09

soulcheck


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.

like image 37
Ethan Furman Avatar answered Sep 21 '22 11:09

Ethan Furman