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.
-
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.
Joan Venge : Thanks. So this will include both 400th and 500th elements?Georg : Only if the upper bound is 501. -
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 ifthousand[501]
is not a valid index.J.F. Sebastian : 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. -
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 ofxrange()
, but in 2.5 and earlier versionsrange()
creates a list whilexrange()
creates a generator, which eats less of your precious RAM.
0 comments:
Post a Comment