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

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
python - Define range for index for lists in for loops - Stack Overflow
I'm a complete beginner in Python. I was coding the "minimum difference between array elements" problem. The idea was to sort the array and then find the difference between adjacent elements, to fi... More on stackoverflow.com
🌐 stackoverflow.com
July 28, 2016
python - Why can't a range object be used to index a list? - Stack Overflow
In Python 3.9, it is not possible to use a range object to index a list. Indeed running the following code, the second print will return an error stating "TypeError: list indices must be integ... More on stackoverflow.com
🌐 stackoverflow.com
python - I want to select specific range of indexes from an array - Stack Overflow
Where x+2 = the first index I want ... the next index number by adding 2 to x and so on. but this didn't work. So my question can I specify numbers to select in a certain order: ... Save this answer. ... Show activity on this post. Numpy slicing allows you to input a list of indices to an array so that you can slice to the exact values you want. ... This will return the 2nd, 4th, 6th, and 8th array elements (keeping in mind that python indices start ... More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
LabEx
labex.io › tutorials › python-how-to-use-index-range-in-python-lists-435401
How to use index range in Python lists | LabEx
In Python, lists are ordered collections of elements that can be accessed using index positions. Each element in a list has a unique index, starting from 0 for the first element.
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-range.html
Python range() Function
The python range(n) function creates a collection of numbers on the fly, like 0, 1, 2, 3 .. n-1. The numbers extend up to, but not including the n, UBNI. The numbers produced by range() are perfect for indexing into collections likes strings and lists.
🌐
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
🌐
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 ...
🌐
freeCodeCamp
freecodecamp.org › news › python-range-function-explained-with-code-examples
Python range() Function – Explained with Code Examples
October 6, 2021 - 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.
Top answer
1 of 3
5

If you really want to use manual indexing, then dont use enumerate() and just create a range() (or xrange() if Python 2.x) of the right size, ie:

for i in xrange(len(a) - 2):
   # code here

Now you don't have to manually take care of indexes at all - if you want to iterate over (a[x], a[x+1]) pairs all you need is zip():

for x, y in zip(a, a[1:]):
   if abs(x - y) < min:
       min = abs(x - y)

zip(seq1, seq2) will build a list of (seq1[i], seq2[i]) tuples (stopping when the smallest sequence or iterator is exhausted). Using a[1:] as the second sequence, we will have a list of (a[i], a[i+1]) tuples. Then we use tuple unpacking to assign each of the tuple's values to x and y.

But you can also just use the builtin min(iterable) function instead:

min(abs(x - y) for x, y in zip(a, a[1:]))

which is the pythonic way to get the smallest value of any sequence or iterable.

Note that with Python 2.x, if your real list is actually way bigger, you'll benefit from using itertools.izip instead of zip

As as side note, using min (actually using any builtin name) as a variable name is possibly not a good idea as it shadows the builtin in the current namespace. If you get a TypeError: 'int' object is not callable message trying this code you'll know why...

2 of 3
3

You can pass a slice of a with the specified start and stop indices to enumerate:

for i, x in enumerate(a[:size-1]):
    ...

i will run from 0 to size-2


On a side note, comments in Python start with # and not //


You can achieve the same results by using min on a generator expression created from the zip of a and its advanced slice:

minimum = min(abs(i - j) for i, j in zip(a, a[1:]))

Also, be careful to not use the name min as this already shadows the builtin min. Something you obviously don't want.

🌐
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.
🌐
Real Python
realpython.com › lessons › indexing-and-slicing
Indexing and Slicing (Video) – Real Python
01:18 If you use an index value that’s too high, Python will raise an exception—an IndexError saying that the list index is out of range.
Published: September 3, 2019
🌐
Stack Overflow
stackoverflow.com › questions › 71506071 › range-index-list-from-end
python - Range Index List from End - Stack Overflow
You can omit the end of the range in order to have it go to the end of the list. I'd suggest using a loop rather than hardcoding the individual ranges, though, especially if cases_inplay is going to shrink over time (e.g. once there are only a few cases you don't need to be printing out cases_inplay[-21:-14]). def case_display(cases): """Print all cases in rows of 7 in descending order of index, but with the cases in ascending order within each row.""" print("-" * 34) for row in range(len(cases) - 7, -1, -7): print(" ".join(f"[{case:02}]" for case in cases[row:row+7])) remainder = len(cases) % 7 if remainder: print(" ".join(f"[{case:02}]" for case in cases[:remainder])) print("-" * 34) cases_inplay = list(range(1, 27)) case_display(cases_inplay)
🌐
Scaler
scaler.com › home › topics › how to fix indexerror - list index out of range in python
How to Fix IndexError - list index out of range in Python | Scaler Topics
February 8, 2024 - We can access element from index = -n to index = (n-1). But here we will access elements from index = 0 to index = n-1. We will use the range function to generate the series of indexes. ... Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.
🌐
CodeWithHarry
codewithharry.com › tutorial › python-list-indexes
List Indexes | Python Tutorial | CodeWithHarry
Here, we have not provided start and end indexes, which means all the values will be considered. But as we have provided a jump index of 2, only alternate values will be printed. Example: printing every 3rd consecutive within a given range
🌐
Rollbar
rollbar.com › home › how to fix python’s “list index out of range” error in for loops
Fix Python List Index Out of Range Error | Rollbar
Fix Python's list index out of range error in for loops with enumerate(), length checks, or -1 to safely access the last item.
Published: June 30, 2026
🌐
Guru99
guru99.com › home › python › python range() function: float, list, for loop examples
Python range() Function: Float, List, For loop Examples
July 10, 2026 - Python range() is a built-in function available with Python from Python (3.x), and it gives a sequence of numbers based on the start and stop index given.