for i in range(15):
    print i #will print out 0..14

for i in range(1, 15):
    print i # will print out 1..14


for i in range (a, b, s):
    print i # will print a..b-1 counting by s. interestingly if while counting by the step 's' you exceed b, it will stop at the last 'reachable' number, example

for i in range(1, 10, 3):
    print i

> 1
> 4
> 7

List Splicing:

a = "hello" # there are 5 characters, so the characters are accessible on indexes 0..4

a[1] = 'e'
a[1:2] = 'e' # because the number after the colon is not reached.

a[x:y] = all characters starting from the character AT index 'x' and ending at the character which is before 'y'

a[x:] = all characters starting from x and to the end of the string

In the future, if you ever wonder what the behavior of python is like, you can try it out in the python shell. just type python in the terminal and you can enter any lines you want (though this is mostly convenient for one-liners rather than scripts).

Answer from Jeremy Fisher on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_lists_access.asp
Python - Access List Items
When specifying a range, the return value will be a new list with the specified items. ... thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) Try it Yourself » · Note: The search will start at index 2 (included) and end at index 5 (not included).
Discussions

Is range(len(list)) ever Pythonic?
I will do it when (1) I need multiple indexes for each iteration (2) The iterations should skip some elements i.e. first and last (3) I don't actually need the value, just the index e.g. something like this for i in range(1, len(array) - 1): array[i] = (array[i-1] + array[i+1]) / 2 More on reddit.com
🌐 r/learnpython
79
83
September 9, 2022
How to get the index range of a list that the values satisfy some criterion in Python? - Stack Overflow
For the first one, you've got an x in there and I'm not sure what it's supposed to be. The second seems to create a list of [None, None, None, None, None, None, None, None] (in Python 2, that is - recreated in Python 3 by wrapping a list() call around the map). More on stackoverflow.com
🌐 stackoverflow.com
python - how to extract a range of index from a list - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Droping data with range of negitive indexes
I’m working with list and list of list. I need to be able to address the data from both ways (right to left and left to right). This is needed when you have a list of lists AND need to address the last ‘sub’ list of the list of lists. Just groups of data. More on discuss.python.org
🌐 discuss.python.org
0
January 14, 2023
🌐
Railsware
railsware.com › home › engineering › indexing and slicing for lists, tuples, strings, other sequential types in python
Python Indexing and Slicing for Lists, Tuples, Strings, other Sequential Types | Railsware Blog
January 22, 2025 - Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well. This is greatly used (and abused) in NumPy and Pandas libraries, which are so popular in Machine Learning and Data Science. It’s a good example of “learn once, use everywhere”. In this article, we will focus on indexing ...
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-range.html
Python range() Function
>>> list(range(2)) [0, 1] >>> list(range(1)) [0] >>> list(range(0)) # n <= 0, no numbers [] >>> list(range(-42)) [] Probably the second most common problem is to go through the standard index numbers, but in reverse order. The reversed() function takes in a linear collection and returns a reversed form of it. This works nicely with range() to go over the regular numbers in reverse order: >>> s = 'Python' >>> len(s) 6 >>> for i in reversed(range(len(s))): ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-list-index
Python List index() - Find Index of Item - GeeksforGeeks
It works by searching through the list from the beginning and returning the index (position) of the first occurrence of the element you're looking for. Example: ... Explanation: index("dog") method finds the first occurrence of "dog" in the ...
Published   April 27, 2025
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.3 documentation
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
🌐
DataCamp
datacamp.com › tutorial › python-list-index
Python List index() Method Explained with Examples | DataCamp
March 28, 2025 - So the syntax is: list_name.index(element, start, stop). Here the start and stop values are optional. In fact, only use it when entirely sure about the range; otherwise, you will get a ValueError, as shown below.
Find elsewhere
🌐
Mimo
mimo.org › glossary › python › range-function
Python range() Function [Python Tutorial]
Using range() to iterate over indices rather than elements avoids creating additional lists and optimizes memory. Particularly in large lists of large objects, accessing items by index can be much more efficient with range(). ... Python 2 has a built-in function called xrange() to create ranges.
🌐
freeCodeCamp
freecodecamp.org › news › python-range-function-explained-with-code-examples
Python range() Function – Explained with Code Examples
October 6, 2021 - If you remember, all iterables in Python follow zero-indexing. This is why it's convenient to use range() to loop through iterables. An iterable of length len has 0, 1, 2, ..., len-1 as the valid indices. So to traverse any iterable, all you need to do is to set the stop value to be equal to len. The sequence you'll get – 0, 1, 2, ..., len-1 – is the sequence of valid indices. ▶ Let's take a more helpful example. You have a list my_list.
🌐
HackerEarth
hackerearth.com › practice › notes › samarthbhargav › a-quick-intro-to-indexing-in-python
A Quick intro to Indexing in Python - Samarth Bhargav
In this section, I'm gonna list a few list indexing idioms that I've found useful. my_list = range(10) new_list = my_list[:] # Create a duplicate list reverse_list = my_list[::-1] # Reverse
🌐
CodeWithHarry
codewithharry.com › tutorial › python-list-indexes
List Indexes | Python Tutorial | CodeWithHarry
The first item has index [0], the second item has index [1], the third item has index [2], and so on. ... As we have seen that list items have an index, we can access items using these indexes.
🌐
freeCodeCamp
freecodecamp.org › news › list-index-out-of-range-python-error-message-solved
List Index Out of Range – Python Error Message Solved
January 20, 2022 - You'll get the Indexerror: list index out of range error when iterating through a list and trying to access an item that doesn't exist. One common instance where this can occur is when you use the wrong integer in Python's range() function.
🌐
Rollbar
rollbar.com › home › how to fix python’s “list index out of range” error in for loops
How to Fix Python’s “List Index Out of Range” Error in For Loops | Rollbar
March 25, 2025 - This error means Python can't find the list position you're asking for. Fix it with enumerate(), proper length checks, or by using -1 to safely get the last item.
Top answer
1 of 5
2
a = [12,11,5,7,2,21,32,13,6,42,1,8,9,0,32,38]
indices = [idx for idx,val in enumerate(a) if val < 10]

This creates a list of indices:

[2, 3, 4, 8, 10, 11, 12, 13]

I would recommend keeping it that way for easy parsing, but you can also turn it into ranges as follows:

ranges = [[]]
for val in indices:
    if not ranges[-1] or ranges[-1][-1] == val-1:
        ranges[-1].append(val)
    else:
        ranges.append([val])

This creates a list of ranges:

[[2, 3, 4], [8], [10, 11, 12, 13]]

Now to take out the middle:

ranges = [[item[0],item[-1]] if len(item) > 1 else item for item in ranges]

Result:

[[2, 4], [8], [10, 13]]
2 of 5
2

You can have your function take a function as an argument to use as the predicate for building your intervals:

def indexscope(dlist, predicate):
    scope = []
    start = end = -1
    for i, v in enumerate(dlist):
        if predicate(v):
            if start == -1:
                start = end = i
                continue
            if end + 1 == i:
                end = i
            else:
                scope.append([start] if start == end else [start, end])
                start = end = i
    if start != -1: 
        scope.append([start] if start == end else [start, end])
    return scope

a = [12,11,5,7,2,21,32,13,6,42,1,8,9,0,32,38]

def less_than_10(n):
    return n < 10

print(indexscope(a, less_than_10))
print(indexscope(a, lambda x: x > 20))


[[2, 4], [8], [10, 13]]
[[5, 6], [9], [14, 15]]

with scipy:

import numpy as np
import scipy.ndimage as nd

def passing_ranges(a, predicate):
    return nd.find_objects(nd.label(predicate(a))[0])

The results are returned as slice objects, but that is to your advantage because you can use them to against your original np array:

small_a = [12,11,5,7,2,21,32,13,6,42,1,8,9,0,32,38]
small_np_array = np.array(small_a)

valid_ranges = passing_ranges(small_np_array, lambda n: n < 10)

for r in valid_ranges:
    print(r[0], small_np_array[r])

slice(2, 5, None) [5 7 2]
slice(8, 9, None) [6]
slice(10, 14, None) [1 8 9 0]

benchmarks

large_a = [12,11,5,7,2,21,32,13,6,42,1,8,9,0,32,38]*1000000
large_np_array = np.array(large_a)

%timeit passing_ranges(large_np_array, lambda x: x < 10)
1 loops, best of 3: 1.2 s per loop

%timeit indexscope(large_a, lambda n: n < 10)
1 loops, best of 3: 6.99 s per loop

Here is your answer, I even inline the predicate to remove a function call:

from itertools import groupby, count

def xibinke(a):
    l = [idx for idx,value in enumerate(a) if value<10]
    return [list(g) for _,g in groupby(l,key=lambda n,c=count():n-next(c))]

%timeit xibinke(large_a)
1 loops, best of 3: 14.6 s per loop
🌐
Rollbar
rollbar.com › home › how to fix indexerror: list index out of range in python
How to Fix "IndexError: list index out of range" in Python
1 month ago - Python lists are zero-indexed, meaning the first element is at index 0, the second is at index 1, and so on. So a list with 4 elements has valid indices 0, 1, 2, and 3 — not 4. ... There are 4 elements in test_list, so the valid indices are ...
🌐
W3Schools
w3schools.com › python › ref_list_index.asp
Python List index() Method
Remove List Duplicates Reverse ... Bootcamp Python Certificate Python Training ... The index() method returns the position at the first occurrence of the specified value....
🌐
Python.org
discuss.python.org › python help
Droping data with range of negitive indexes - Python Help - Discussions on Python.org
January 14, 2023 - I’m working with list and list of list. I need to be able to address the data from both ways (right to left and left to right). This is needed when you have a list of lists AND need to address the last ‘sub’ list of the …
🌐
Google
developers.google.com › google for education › python › python lists
Python Lists | Python Education | Google for Developers
January 23, 2026 - Python's built-in list type is defined using square brackets [ ] and elements are accessed using zero-based indexing. Assigning one list variable to another makes both variables point to the same list in memory.