: 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
๐ŸŒ
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 reverse the order of rows, depending on the number under the second colon. The following points need to be remembered when slicing arrays with colons:
Author ย  Curtis Miller
Published ย  2018
Pages ย  168
๐ŸŒ
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.
๐ŸŒ
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, ...
๐ŸŒ
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?

Find elsewhere
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.

๐ŸŒ
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...
๐ŸŒ
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.
๐ŸŒ
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 ...
๐ŸŒ
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,:])
๐ŸŒ
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 ...
๐ŸŒ
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.
๐ŸŒ
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).
๐ŸŒ
Medium
melodyxu.medium.com โ€บ the-confusing-double-colon-in-numpy-850093adc36f
The Confusing Double Colon (::) in NumPy | by Melody Xu | Medium
August 25, 2019 - The Confusing Double Colon (::) in NumPy Starting from the basic. Indexing/Slicing in NumPy has this formula [start:stop:step] Example 1: y = [1,2,3,4,5,6] y[2:6:3] Output is [3,6] This means โ€ฆ
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ what is:: (double colon) in python when subscripting sequences?
What is:: (double colon) in Python when subscripting sequences? - AskPython
April 23, 2023 - Here, the interpreter executed and printed index 9 to index 16. However, we can reduce the range by using the operator :: However, you may refer to the code to acquire the result: ... The operator :: in front indicates that any start or end indices have not been specified. This particular documentation assisted me to extract a few pieces of information. To know more about Double Colon :: Operator refers to this article ยท Hereโ€™s an article on Slicing arrays with colons that also can be used for slicing tuples and strings.
๐ŸŒ
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.