简体   繁体   中英

Is there a way to loop through a sub section of a list in Python

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM