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
... 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).
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-range.html
Python range() Function
>>> list(range(10, 5, -1)) [10, 9, 8, 7, 6] >>> list(range(10, 5, -2)) [10, 8, 6] >>> list(range(6, 5, -2)) [6] >>> list(range(5, 5, -2)) # equal to stop is omitted [] >>> list(range(4, 5, -2)) # beyond the stop is omitted [] If you want to loop over the index numbers of a string or list backwards, ...
🌐
DataCamp
datacamp.com › tutorial › python-list-index
Python List index() Method Explained with Examples | DataCamp
March 28, 2025 - You can use the len() function to get the length of a list and check if an index is within the range of valid indices. The "list indices must be integers" error occurs when you try to use a non-integer value as a list index. For example, if you try to use a floating-point number or a string as a list index, you will get this error.
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
🌐
freeCodeCamp
freecodecamp.org › news › python-range-function-explained-with-code-examples
Python range() Function – Explained with Code Examples
October 6, 2021 - Notice how my_list is 7 items long, and the indices obtained are from 0 through 6, as expected. Sometimes, you may need to use negative integers instead. In this case, if you use only the stop argument, you'll not get the desired output, though the code doesn't throw an error. This is because the default start value is assumed to be 0, and you cannot count up from 0 to -5. for index in range(-5): print (index) #Output #NOTHING HERE
🌐
LabEx
labex.io › tutorials › python-how-to-use-index-range-in-python-lists-435401
How to use index range in Python lists | LabEx
## Using generators for memory-efficient slicing def efficient_slice(lst, start, end): return (x for x in lst[start:end]) large_list = list(range(1000000)) small_slice = list(efficient_slice(large_list, 10, 20)) print(small_slice) ## Output: ...
🌐
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 ...
Find elsewhere
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-list-index
Python List index() - Find Index of Item - GeeksforGeeks
Example 1: In this example, we are searching for the index of the number 40 within a specific range of the list from index 4 to 7 .
Published   April 27, 2025
🌐
CodeWithHarry
codewithharry.com › tutorial › python-list-indexes
List Indexes | Python Tutorial | CodeWithHarry
We will see this in given examples. Example: printing elements within a particular range: animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"] print(animals[3:7]) # using positive indexes print(animals[-7:-2]) # using negative indexes
🌐
Flexiple
flexiple.com › python › list-index-out-of-range-python
List Index Out of Range – Python Error [Solved] - Flexiple - Flexiple
For example, in the list colors = ['red', 'green', 'blue'], colors[0] returns 'red', the first element. Negative Indexing: Python also supports negative indexing, which starts from the end of the list.
🌐
Mimo
mimo.org › glossary › python › range-function
Python range() Function [Python Tutorial]
If you prefer, you can also catch errors using a try...except statement. Python · Open in Mimo · Open in Mimo · Copy Code · example_list = [1, 2, 3] for item in example_list: print(item) try: for i in range(3): print(example_list[i]) except IndexError: print(f"Index {i} is out of range") ...
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
For example, let’s say we’re printing out president names along with their numbers (based on list indexes). We could use range(len(our_list)) and then lookup the index like before: But there’s a more idiomatic way to accomplish this task: use the enumerate function. Python’s built-in ...
🌐
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 - With the total values of the list above being 4, the index range is 0 to 3. Now, let's try to access an item using negative indexing. Say I want to access the first item in the list, "Kelly", by using negative indexing. names = ["Kelly", "Nelly", ...
🌐
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 …
🌐
Coursera
coursera.org › tutorials › python-range
How to Use Range in Python | Coursera
Lazy evaluation helps code run ... to get the value at a specified position. For example, suppose you’re working with range(2, 10, 2)....