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.
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.
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.
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.