Numpy slicing allows you to input a list of indices to an array so that you can slice to the exact values you want.

For example:

    import numpy as np
    a = np.random.randn(10)
    a[[2,4,6,8]]

This will return the 2nd, 4th, 6th, and 8th array elements (keeping in mind that python indices start from 0). So, if you want every 2nd element starting from an index x, you can simply populate a list with those elements and then feed that list into the array to get the elements you want, e.g:

    idx = list(range(2,10,2))
    a[idx]

This again returns the desired elements (index 2,4,6,8).

Answer from enumaris on Stack Overflow
🌐
freeCodeCamp
freecodecamp.org › news › python-range-function-explained-with-code-examples
Python range() Function – Explained with Code Examples
October 6, 2021 - You can use the above line of code to get a sequence from 0 through stop-1 : 0, 1, 2, 3,..., stop-1. ▶ Consider the following example where you call range() with 5 as the argument. And you loop through the returned range object using a for loop to get the indices 0,1,2,3,4 as expected. for index in range(5): print(index) #Output 0 1 2 3 4 · If you remember, all iterables in Python ...
Discussions

Range of indexes
List slice notation [start:end] means beginning at index start going up to but excluding end. It's the same for several other things like range(start, end). This might seem weird, but has some benefits. For example you can combine ranges without causing any overlap. You can also use len(...) as the end-index without going out of bounds. If end was inclusive you'd need adjustments of +/-1 much more often. More on reddit.com
🌐 r/learnpython
6
5
October 2, 2023
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 find the one with the minimum difference. However, I wonder how to define the range for the index of the ... More on stackoverflow.com
🌐 stackoverflow.com
July 28, 2016
How to get the index range of a list that the values satisfy some criterion in Python? - Stack Overflow
I'm still not clear if it is built-in ... in the python document. ... Save this answer. ... Show activity on this post. Copya = [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] ... I would recommend keeping it that way for easy parsing, but you can also turn it into ranges as ... More on stackoverflow.com
🌐 stackoverflow.com
arrays - Python: how to find a range of indexes from small to large? - Stack Overflow
I have 2 arrays. First is an array of rows. Second is an array of indents (think indenting text in a Word document) 1. ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] 2. ['1', '2', '3', '1', '... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.RangeIndex.html
pandas.RangeIndex — pandas 3.0.3 documentation - PyData |
Immutable Index implementing a monotonic integer range. RangeIndex is a memory-saving special case of an Index limited to representing monotonic ranges with a 64-bit dtype.
🌐
YouTube
youtube.com › watch
Range of indexes in Python Lists | Amit Thinks - YouTube
In this video, learn how to set the Range of indexes in Python Lists. Lists in Python are ordered. It is modifiable and changeable, unlike Tuples. Python Ful...
Published   August 24, 2022
🌐
DataCamp
datacamp.com › tutorial › python-list-index
Python List index() Method Explained with Examples | DataCamp
March 28, 2025 - To avoid the "list index out of range" error, you should make sure that the index you are trying to access is within the range of valid indices for the list.
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.

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
Top answer
1 of 1
1

I believe this accomplishes what you want, if I interpreted your question correctly:

indents = ['1', '2', '3', '1', '2', '2', '2', '2', '1', '2']

arraySaved = []; temp = [0] #Initialize temporary list
for idx, i in enumerate(indents):
    if idx==len(indents)-1:
        temp.append(idx)
        arraySaved.append(temp) #Reached end of list
    elif indents[idx+1]<i: #Ending index of temporary list
        temp.append(idx)
        arraySaved.append(temp) #Store temporary list
        temp = []; temp.append(idx+1) #Reset temporary list and begin new one

print(arraySaved)

Yields:

[[0, 2], [3, 7], [8, 9]]

Keep in mind that your desired output is the upper and lower bounds of the row indices after being separated into individually increasing indent counts. Therefore, you do not actually need the list rows, since you can just enumerate the list indents. The answer above is equivalent to your desired output if you keep in mind that Python indexes from 0, not 1.

Figured I would add that if you really want the row numbers indexed from 1, then you can do the following:

arraySaved = [[i+1 for i in j] for j in arraySaved]

Gives:

[[2, 3], [4, 8], [9, 10]]

Explanation

temp is simply a list used to temporarily store the indices of the values in indents that correspond to the starting and ending indices for each individual outputted list eventually stored in arraySaved. We need to initialize temp as well with the first index of the list, i.e. 0.

for idx, i in enumerate(indents): simply loops through the values inside of the list indents, where enumerate also unpacks the indices of the values inside of the list as well

The first if statement accounts for the case that the current index in the loop is the last one in the list, because then idx+1 would exceed the dimensions of the list being iterated on. If either of the criteria in the if statements are satisfied, then the current index is stored in the temp variable. If the ending index criteria is satisfied then the temp list is reset after being appended to arraySaved.

Hope that helps!

🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-range.html
Python range() Function
The most common form is range(n), given integer n returns a numeric series starting with 0 and extending up to but not including n, e.g. range(6) returns 0, 1, 2, 3, 4, 5. With Python's zero-based indexing, the contents of a string length 6, are at index numbers 0..5, so range(6) will produce ...
🌐
W3Schools
w3schools.com › python › python_lists_access.asp
Python - Access List Items
Python Examples Python Compiler ... ... Note: The first item has index 0. ... You can specify a range of indexes by specifying where to start and where to end the range....
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
I often see new Python programmers attempt to recreate traditional for loops in a slightly more creative fashion in Python: This first creates a range corresponding to the indexes in our list (0 to len(colors) - 1).
🌐
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 - So, here is our first example of a slice: 2:7. The full slice syntax is: start:stop:step. start refers to the index of the element which is used as a start of our slice. stop refers to the index of the element we should stop just before to finish our slice. step allows you to take each nth-element within a start:stop range.
🌐
LabEx
labex.io › tutorials › python-how-to-use-index-range-in-python-lists-435401
How to use index range in Python lists | LabEx
Python provides powerful list indexing capabilities that allow developers to efficiently access, manipulate, and extract data from lists. This tutorial explores the fundamental techniques and advanced methods of using index ranges in Python lists, helping programmers unlock more sophisticated ...
🌐
Guru99
guru99.com › home › python › python range() function: float, list, for loop examples
Python range() Function: Float, List, For loop Examples
August 12, 2024 - What is Python Range? 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. In case the start index
🌐
Real Python
realpython.com › python-range
Python range(): Represent Numerical Ranges – Real Python
November 24, 2024 - You can use Python’s square bracket notation to pick out a single element from a range: ... You first construct a range that contains the odd numbers below twenty. Then you pick out the number at index three. Since Python sequences are zero-indexed, this is the fourth odd number, namely seven.
🌐
Coursera
coursera.org › tutorials › python-range
How to Use Range in Python | Coursera
Since Python indexes from the 0 position, the third value would be in the second position and would be 31. Python range is a function that returns a sequence of numbers.