tags:

views:

288

answers:

3

So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?

I don't see a way by using the for each and for range techniques.

+7  A: 
for element in allElements[400:501]:
     # do something

These are slices and generate a sublist of the whole list. They are one of the main elements of Python.

Georg
Thanks. So this will include both 400th and 500th elements?
Joan Venge
Only if the upper bound is 501.
Georg
+21  A: 
for x in thousand[400:500]:
    pass

If you are working with an iterable instead of a list, you should use itertools:

import itertools
for x in itertools.islice(thousand, 400, 500):
    pass

If you need to loop over thousand[500], then use 501 as the latter index. This will work even if thousand[501] is not a valid index.

joeforker
It's worth mentioning that `alist[istart:iend]` creates a completely new list with a shallow copy of all elements from `alist` between `istart` and `iend` indices. It is a O(iend-istart) operation.
J.F. Sebastian
+2  A: 

Using

for element in allElements[400:501]:
    doSomething(element)

makes Python create new object, and might have some impact on memory usage.

Instead I'd use:

for index in xrange(400, 501):
    doSomething(allElements[index])

This way also enables you to manipulate list indexes during iteration.

EDIT: In Python 3.0 you can use range() instead of xrange(), but in 2.5 and earlier versions range() creates a list while xrange() creates a generator, which eats less of your precious RAM.

Abgan