Is there a way to iterate over a list subsector in Python

So, for a list with 1000 elements, I want a cycle from 400 to 500. How do you do this?

I do not see the way, using for each and for range methods.

+3
source share
3 answers
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 last index. This will work even if thousand[501]it is not a valid index.

+22
source
for element in allElements[400:501]:
     # do something

. Python.

+7

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

Python .

Instead, I would use:

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

This method also allows you to manipulate list indices during iteration.

EDIT: in Python 3.0 you can use range()instead xrange(), but in version 2.5 and earlier it range()creates a list and xrange()creates a generator that eats less than your precious memory.

+2
source

Source: https://habr.com/ru/post/1702845/


All Articles