The syntax is:

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:stop:step] # start through not past stop, by step

The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default).

The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

Similarly, step may be a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

Relationship with the slice object

A slice object can represent a slicing operation, i.e.:

a[start:stop:step]

is equivalent to:

a[slice(start, stop, step)]

Slice objects also behave slightly differently depending on the number of arguments, similar to range(), i.e. both slice(stop) and slice(start, stop[, step]) are supported. To skip specifying a given argument, one might use None, so that e.g. a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)].

While the :-based notation is very helpful for simple slicing, the explicit use of slice() objects simplifies the programmatic generation of slicing.

Answer from Greg Hewgill on Stack Overflow
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_slicing.asp
NumPy Array Slicing
Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end]. We can also define the step, like this: [start:end:step]. ... Note: The result includes the start index, ...
Top answer
1 of 16
6657

The syntax is:

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:stop:step] # start through not past stop, by step

The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default).

The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

Similarly, step may be a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

Relationship with the slice object

A slice object can represent a slicing operation, i.e.:

a[start:stop:step]

is equivalent to:

a[slice(start, stop, step)]

Slice objects also behave slightly differently depending on the number of arguments, similar to range(), i.e. both slice(stop) and slice(start, stop[, step]) are supported. To skip specifying a given argument, one might use None, so that e.g. a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)].

While the :-based notation is very helpful for simple slicing, the explicit use of slice() objects simplifies the programmatic generation of slicing.

2 of 16
728

The Python tutorial talks about it (scroll down a bit until you get to the part about slicing).

The ASCII art diagram is helpful too for remembering how slices work:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5
  -6  -5  -4  -3  -2  -1

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n.

Discussions

Python: slicing a multi-dimensional array - Stack Overflow
@mgilson I get it now, under normal circumstances a[:] is a copy and is used to avoid having multiple pointers referencing the same memory location. I just confused C and python syntax. 2016-05-11T09:24:48.53Z+00:00 ... To slice a multi-dimensional array, the dimension (i.e. More on stackoverflow.com
🌐 stackoverflow.com
Does array slicing [::] use extra memory?
Python list slicing should be creating a new list (use more memory). You can see the implementation of that here . I think what you read regarding slicing may be for NumPy arrays where slices create “views” and not copies. More on reddit.com
🌐 r/Python
9
3
December 13, 2021
Array slicing notation to get N elements from index I - Ideas - Discussions on Python.org
Hi - my first post here 🙂 I’ve had a search through PEPs, forums, and at work but haven’t been able to prove the negative that this syntactic sugar doesn’t exist. Frequently I need to get an array slice in the form: arr[start_idx:(start_idx + some_length)] The repetition of the start_idx ... More on discuss.python.org
🌐 discuss.python.org
1
April 24, 2023
Why isn't slicing out of range?
Hi, First of all, please understand that I wrote it using a translator. I’m using Python version 3.11.1 alpha=‘abcdef’ alpha[7] => out of range alpha[0:99] => ‘abcdef’ If you look at the above, indexing causes errors when out of range, but slicing does not cause errors when out of index. More on discuss.python.org
🌐 discuss.python.org
1
February 9, 2023
🌐
freeCodeCamp
freecodecamp.org › news › python-slicing-how-to-slice-an-array
Python Slicing – How to Slice an Array and What Does [::-1] Mean?
December 8, 2022 - Typecodes gotten from the Python documentation. ... We created an array of integer values from 1 to 5 here. We also accessed the second value by using square brackets and its index in the order, which is 1. Let's say you want to slice a portion of this array and assign the slice to another variable.
Top answer
1 of 4
102

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

2 of 4
2

To slice a multi-dimensional array, the dimension (i.e. axis) must be specified. As OP noted, arr[i:j][i:j] is exactly the same as arr[i:j] because arr[i:j] sliced along the first axis (rows) and has the same number of dimensions as arr (you can confirm by arr[i:j].ndim == arr.ndim); so the second slice is still slicing along the first dimension (which was already done by the first slice). To slice along the second dimension, it must be explicitly specified, e.g.:

arr[:2][:, :2]                   # its output is the same as `arr[:2, :2]`

A bare : means slice everything in that axis, so there's an implicit : for the second axis in the above code (i.e. arr[:2, :][:, :2]). What the above code is doing is slicing the first two rows (or first two arrays along the first axis) and then slice the first two columns (or the first two arrays along the second axis) from the resulting array.

An ... can be used instead of multiple colons (:), so for a general n-dimensional array, the following produce the same output:

w = arr[i:j, m:n]
x = arr[i:j, m:n, ...]
y = arr[i:j][:, m:n]
z = arr[i:j, ...][:, m:n, ...]

That said, arr[:2, :2] is the canonical way because in the case of arr[i:j][:, i:j], arr[i:j] creates a temporary array which is indexed by [:, i:j], so it's comparatively inefficient.

However, there are cases where chained indexing makes sense (or readable), e.g., if you want to index a multi-dimensional array using a list of indices. For example, if you want to slice the top-left quarter of a 4x4 array using a list of indices, then chained indexing gives the correct result whereas a single indexing gives a different result (it's because of numpy advanced indexing) where the values correspond to the index pair for each position in the index lists.

arr = np.arange(1,17).reshape(4,4)
rows = cols = [0,1]
arr[rows][:, cols]               # <--- correct output
arr[rows, cols]                  # <--- wrong output
arr[[[e] for e in rows], cols]   # <--- correct output
arr[np.ix_(rows, cols)]          # <--- correct output
🌐
CodeSignal
codesignal.com › learn › courses › numpy-basics › lessons › array-indexing-and-slicing-in-numpy
Array Indexing and Slicing in NumPy - Python
Note that [-1] gives us the last element, the same as with plain Python's lists! ... Array slicing lets us access a subset, or slice, of an array.
🌐
Data Dependence
datadependence.com › 2016 › 05 › python-sequence-slicing-guide
A Quick Guide to Slicing in Python – Become a Python Ninja
July 6, 2016 - Slicing has incredibly simple syntax; after a sequence type variable inside square brackets you define a start point, an end point and a step, separated by colons like so; var[start:end:step]. However it doesn’t work the way you might first ...
Find elsewhere
🌐
StrataScratch
stratascratch.com › blog › numpy-array-slicing-in-python
NumPy Array Slicing in Python
March 1, 2024 - Slicing 1D arrays in NumPy is straightforward. You specify the start, stop, and step within square brackets to select a portion of the array. ... The first slice arr[:5] selects the first five elements of the array, demonstrating how omitting the start index defaults to 0.
🌐
Reddit
reddit.com › r/python › does array slicing [::] use extra memory?
r/Python on Reddit: Does array slicing [::] use extra memory?
December 13, 2021 -

Trying to wrap my head around this merge sort implementation:

def mergeSort(myList):
    if len(myList) > 1:
        mid = len(myList) // 2
        left = myList[:mid]
        right = myList[mid:]

        # Recursive call on each half
        mergeSort(left)
        mergeSort(right)

        # Two iterators for traversing the two halves
        i = 0
        j = 0
        
        # Iterator for the main list
        k = 0
        
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
              # The value from the left half has been used
              myList[k] = left[i]
              # Move the iterator forward
              i += 1
            else:
                myList[k] = right[j]
                j += 1
            # Move to the next slot
            k += 1

        # For all the remaining values
        while i < len(left):
            myList[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            myList[k]=right[j]
            j += 1
            k += 1

Here we get the mid point, create a left array with myList[:mid] and right array with myList[mid:], then we loop through each half and change myList based on which current element is smaller.

What I don't understand is, I read that array slicing in python does not create a new array, so when we change myList, how come it doesn't the lists left and right? If the sliced arrays are independent from the original, does that mean python uses a list to store memory locations for each element? How much memory does that use? Wouldn't that use almost as much as a new array for an array of ints anyway?

🌐
Canard Analytics
canardanalytics.com › blog › index-slicing-numpy-arrays
Indexing and Slicing NumPy Arrays | Canard Analytics
July 10, 2022 - Slicing syntax is written [start:stop:step]. If start is omitted then slicing starts from the first item (index 0). If stop is omitted then slicing will be considered from start to the end of the array. If step is omitted then the stepping interval is considered to be 1. We'll use the 4 x 5 ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-slicing-multi-dimensional-arrays
Python slicing multi-dimensional arrays - GeeksforGeeks
July 23, 2025 - In this example, we first create a 3-D NumPy array called array_3d. Then, we use negative indexing to slice the last row from each 2-D matrix within the 3-D array.
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › brackets › slicing.html
[] (slicing) — Python Reference (The Right Way) 0.1 documentation
>>> # when using extended slice syntax both chunks must match >>> l = [0, 1, 2, 3] >>> l[::2] = "ABCD" Traceback (most recent call last): File "<interactive input>", line 1, in <module> ValueError: attempt to assign sequence of size 4 to extended slice of size 2
🌐
Python.org
discuss.python.org › ideas
Array slicing notation to get N elements from index I - Ideas - Discussions on Python.org
April 24, 2023 - Hi - my first post here 🙂 I’ve had a search through PEPs, forums, and at work but haven’t been able to prove the negative that this syntactic sugar doesn’t exist. Frequently I need to get an array slice in the form: arr[start_idx:(start_idx + some_length)] The repetition of the start_idx ...
🌐
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, ...
🌐
Python.org
discuss.python.org › python help
Why isn't slicing out of range? - Python Help - Discussions on Python.org
February 9, 2023 - Hi, First of all, please understand that I wrote it using a translator. I’m using Python version 3.11.1 alpha=‘abcdef’ alpha[7] => out of range alpha[0:99] => ‘abcdef’ If you look at the above, indexing causes errors when out of range, but slicing does not cause errors when out of index.
🌐
Nanyang Technological University
libguides.ntu.edu.sg › python › arrayslicing
NP.4 Array Slicing - Python for Basic Data Analysis - LibGuides at Nanyang Technological University
July 22, 2025 - Array slicing is similar to list slicing in Python. Array indexing also begins from 0. However, since arrays can be multidimensional, we have to specify the slice for each dimension. As we are mainly working with 2 dimensional arrays in this guide, we need to specify the row and column like ...
🌐
W3Schools
w3schools.com › python › python_strings_slicing.asp
Python - Slicing Strings
Use negative indexes to start the slice from the end of the string: ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
DataCamp
datacamp.com › doc › numpy › array-slicing
NumPy Array Slicing
Array slicing is utilized when ... slicing syntax follows the format array[start:stop:step], where start is the index to begin the slice, stop is the index to end the slice (exclusive), and step defines the interval between elements....
🌐
The Python Coding Stack
thepythoncodingstack.com › p › a-python-slicing-story
A Slicing Story - by Stephen Gruppetta
September 24, 2023 - Now, let's replicate these steps using NumPy arrays. You'll need to install NumPy using pip install numpy or your favourite package manager: The behaviour when you slice a NumPy array is different to the case when you slice a list. When you assign a new value to an item in subset_of_numbers_array, the original array also changes.
🌐
Problem Solving with Python
problemsolvingwithpython.com › 05-NumPy-and-Arrays › 05.06-Array-Slicing
Array Slicing - Problem Solving with Python
Therefore, the slicing operation [:2] pulls out the first and second values in an array. The slicing operation [1:] pull out the second through the last values in an array.
🌐
Pythonhealthdatascience
pythonhealthdatascience.com › content › 01_algorithms › 03_numpy › 03_slicing.html
Array slicing and indexing — Python for health data science.
Originally we were restricting our slice to the 1st element i.e. k=0 of each array returned. If we want all elements we replace the 0 with : ... Getting to grips with multi-dimensional arrays takes time and practice. So do persevere. If you have only ever coded in python before and have no experience of a lower level language like C++ or Rust then the behaviour of arrays and slices can catch you out.