: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

Answer from soulseekah on Stack Overflow
🌐
AskPython
askpython.com › home › colon in python – why do we use (:) in python?
Colon in Python - Why do we use (:) in Python? - AskPython
February 22, 2021 - A colon (:) holds a lot of importance in Python. A colon in Python is used for multiple functions including declaring functions, fetching data, array indexing, and more.
🌐
O'Reilly
oreilly.com › library › view › hands-on-data-analysis › 9781789530797 › 97ebee6a-7efb-479e-94b8-1f0f174c49fb.xhtml
Slicing arrays with colons - Hands-On Data Analysis with NumPy and pandas [Book]
June 29, 2018 - Remember that when the spot before or after the colon is left blank, Python treats the index as extending to either the beginning or the end of the dimension. A second colon can be specified to instruct Python to, say, skip every other row or ...
Author   Curtis Miller
Published   2018
Pages   168
🌐
Hpc-carpentry
hpc-carpentry.org › hpc-python › 03-lists › index.html
Numpy arrays and lists – Introduction to High-Performance Computing in Python
January 20, 2023 - Note that in Python, all indices ... the first position — the first element does not require an offset to get to. ... Note that we can index a range using the colon (:) operator....
🌐
freeCodeCamp
forum.freecodecamp.org › python
What is the colon in this code doing? - Python - The freeCodeCamp Forum
November 20, 2022 - Can anyone explain this? It’s from FreeCodeCamps video tutorial. I have no idea what the colon dose in this part of the code [i*3:(i+1) * 3] · Basically selecting the items in the list ‘board’ that have indexes equal to the values in the range: · The use of the colon is the main thing ...
🌐
Utexas
johnfoster.pge.utexas.edu › numerical-methods-book › ScientificPython_Numpy.html
NumPy: Numerical Python
September 8, 2020 - An explanation of the notation used in the operation above: the comma (,) separates dimensions of the array in the indexing operation. The colon (:) represents all of that dimension. So is this operation, the colon signifies getting all rows, ...
Top answer
1 of 3
16

As suggested from numpy's documentation about indexing you can use the slice built-in function and tuple concatenation to create variable indexes.

In fact the : in the subscript is simply the literal notation for a slice literal.

In particular : is equivalent to slice(None) (which, itself, is equivalent to slice(None, None, None) where the arguments are start, stop and step).

For example:

a[(0,) * N + (slice(None),)]

is equivalent to:

a[0, 0, ..., 0, :]   # with N zeros

The : notation for slices can only be used directly inside a subscript. For example this fails:

In [10]: a[(0,0,:)]
  File "<ipython-input-10-f41b33bd742f>", line 1
    a[(0,0,:)]
           ^
SyntaxError: invalid syntax

To allow extracting a slice from an array of arbitrary dimensions you can write a simple function such as:

def make_index(num_dimension, slice_pos):
    zeros = [0] * num_dimension
    zeros[slice_pos] = slice(None)
    return tuple(zeros)

And use it as in:

In [3]: a = np.array(range(24)).reshape((2, 3, 4))

In [4]: a[make_index(3, 2)]
Out[4]: array([0, 1, 2, 3])

In [5]: a[make_index(3, 1)]
Out[5]: array([0, 4, 8])

In [6]: a[make_index(3, 0)]
Out[6]: array([ 0, 12])

You can generalize make_index to do any kind of things. The important thing to remember is that it should, in the end, return a tuple containing either integers or slices.

2 of 3
2

You could compose an string with the code selecting the dimension you want and use eval to execute that code string.

An start is:

n = 2
sel = "0,"*(n-1) + ":"
eval('x[' + sel + ']')

To get exactly what you want, thinks are a little bit more complicated (but not so much):

ind = 2
n = 3
sel = "".join([ ("0" if i != ind else ":") + ("," if i < n-1 else "") for i in xrange(n)])
eval('x[' + sel + ']')

It is the same strategy that is used for Dynamic SQL.

Find elsewhere
🌐
Sololearn
sololearn.com › en › Discuss › 2480240 › numpy-arrays-colon-usage
Numpy array's colon usage | Sololearn: Learn to code for FREE!
# new_record is the name of the numpy array new_record = np.array ([[188, 190, 189, 165, 180], [58, 62, 55, 68, 80]]) new_record.shape >>> (2, 5) heights_and_ages_arr[:2, :5 ] = new_record The meaning of a numpy array's colon seems to be a little different than that of a regular array's colon. Would it be correct to interpret the final line in the above code as selecting everything in row index up to but not including index 2, and from column index up to but not including index 5? pythonnumpy: 4th Sep 2020, 5:25 PM ·
🌐
Julia Programming Language
discourse.julialang.org › general usage
Slicing arrays with a Colon via PythonCall - General Usage - Julia Programming Language
June 3, 2024 - This works in Julia julia> rand(3,5)[:, 1] and this works in Python >>> import numpy as np >>> np.random.rand(3,5)[:, 1] but this doesn’t work with PythonCall julia> using PythonCall julia> np = pyimport("numpy") julia> np.random.rand(3,5)[:, 1] ERROR: Python: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices Python stacktrace: none Stacktrace: [1] pythrow() @ PythonCall.Core ~/.julia/packages/PythonCall/S5M...
🌐
HashBangCode
hashbangcode.com › article › slicing-arrays-and-strings-using-colon-operator-python
Slicing Arrays and Strings Using The Colon Operator In Python | #! code
We can simplify this by just passing in the third parameter and using the double colon syntax (::). If we pass in '2' as the parameter then we essentially get every odd item in the array (since the count starts at 0). The following two lines are identical since Python assumes that we mean the start and end of the array if we miss out those arguments.
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › how to use colon (:) in list in python (2 examples)
How to Use Colon Operator (:) in List in Python | Slicing Example
June 19, 2023 - As shown in the example, the colon operator selected the elements from index 1 to index 4 (not including) in my_list, resulting in a new sliced_list.
🌐
NumPy
numpy.org › doc › stable › user › basics.indexing.html
Indexing on ndarrays — NumPy v2.4 Manual
The simplest case of indexing with N integers returns an array scalar representing the corresponding item. As in Python, all indices are zero-based: for the i-th index \(n_i\), the valid range is \(0 \le n_i < d_i\) where \(d_i\) is the i-th element of the shape of the array.
🌐
Reddit
reddit.com › r/learnpython › double colon notation for lists
r/learnpython on Reddit: Double colon notation for lists
May 5, 2020 -

If I have a list l= list(range(1,11)) then if I want a slice of the odd numbers then l[::2] will return the odd numbers. My question is does the first colon mean start from index 0, the second to stop at the end of the list and 2 means the step size?

🌐
TutorialsPoint
tutorialspoint.com › what-does-colon-operator-do-in-python
What does colon ':' operator do in Python?
The − operator slices a part from a sequence object such as list, tuple or string. It takes two arguments. First is the index of start of slice and second is index of end of slice. Both operands are optional. If first operand is omitted, it is 0 by default.
🌐
Data-apis
data-apis.org › array-api › 2022.12 › API_specification › indexing.html
Indexing — Python array API standard 2022.12 documentation
Colons : must be used for slices: start:stop:step, where start is inclusive and stop is exclusive. ... The specification does not support returning scalar (i.e., non-array) values from operations, including indexing. In contrast to standard Python indexing rules, for any index, or combination ...
🌐
Medium
melodyxu.medium.com › the-confusing-double-colon-in-numpy-850093adc36f
The Confusing Double Colon (::) in NumPy | by Melody Xu | Medium
August 25, 2019 - This means starting from index 2 which is number 3 in the array and goes all the way till index 6, which is number six and skip by 2.
🌐
Problem Solving with Python
problemsolvingwithpython.com › 05-NumPy-and-Arrays › 05.06-Array-Slicing
Array Slicing - Problem Solving with Python
The code section below slices out the first two rows and all columns from array a. ... Again, a blank represents defaults the first index or the last index. The colon operator all by itself also represents "all" (default start: default stop).
🌐
Reddit
reddit.com › r/learnpython › how to unpack a list of colons and numpy nones to index an array?
r/learnpython on Reddit: How to unpack a list of colons and NumPy Nones to index an array?
October 27, 2022 -

Hello! I am writing a program that will have an arbitrary number of `:` and `None` in arbitrary locations of an n-dimensional NumPy array. Therefore, I want a way to unpack these `:` and `None` axis operators into the `[]` that indexes an array and auto-populates certain axes according to where the `:` and `None` are. According to Pylance:

Unpack operator in subscript requires Python 3.11 or newerPylance

However, while using Python 3.11, I get the following error:

Traceback (most recent call last):
  File "/home/.../quant.py", line 261, in <module>
    print(arr[*lhs_axes] + arr2[None,None,:])
          ~~~^^^^^^^^^^^
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Current code:

import numpy as np 
if __name__ == "__main__":
    lhs_ind, rhs_ind = 'ij', 'k'
    lhs_axes = [':' for i in lhs_ind]
    lhs_axes.append(None)
    
    arr1 = np.ones((2,2))
    arr2 = np.ones(2)
    print(arr1[*lhs_axes] + arr2[None,None,:])
🌐
Google Groups
groups.google.com › g › julia-dev › c › ze38WWEbbIY
using ':' (colon) in a variable for indexing
However, that is a slightly different ... of slice object like python does. It could be just a range in simple cases but something more complicated when an 'end' features. Then one could build up slices without an array and pass them around. sli = colon(start, step, end) and it ...