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
6664

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

A Comprehensive Guide to Slicing in Python
The start/end indexing when going in reverse has always taken a level of extra mental effort that I don't like. Like excluding the first and last item using [1:-1] is intuitive to me, but doing the same in reverse by doing [-2:0:-1] annoys me (though I do get why its like that). That is why I tend to do [1:-1][::-1] instead. More on reddit.com
🌐 r/Python
40
356
February 1, 2022
Slicing 2D Numpy arrays
You have to understand slices: they have the structure start:stop:step, where start tells you the index from where you'll get the values; stop tells you the next to last index for the values (meaning that your last index will be the previous one, not this), and step will give you the distance between elements. So, 1:2 tells you from the row 1 to the row 2 without including row 2. That gives you just row 1. More on reddit.com
🌐 r/PythonLearning
9
3
August 11, 2024
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
Python: Slicing lists

Nevermind I understand it now

More on reddit.com
🌐 r/learnprogramming
5
3
May 30, 2019
🌐
Pythonhealthdatascience
pythonhealthdatascience.com › content › 01_algorithms › 03_numpy › 03_slicing.html
Array slicing and indexing — Python for health data science.
Going back to slicing we can understand the dimensions. Here’s a reminder fo the full array: ... Task: slice td so that we have the vector [13, 23, 33] i.e. the [i, 1, 0] elements where i is the row.
🌐
CodeSignal
codesignal.com › learn › courses › numpy-basics › lessons › array-indexing-and-slicing-in-numpy
Array Indexing and Slicing in NumPy - Python
, of an array. The basic syntax for slicing in Python is · . Join the 1M+ learners on CodeSignal · Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignalStart learning today! slice · array[start:stop:step] Let's check this out: As a reminder, stop is not included, so [1:4] gives us elements with indices 1, 2, 3.
🌐
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 - It's also worth noting that the slicing action does not affect the original array. With slicing, you only "copy a portion" of the original array. For example, if you want to slice an array from a specific start value to the end of the array, here's how:
🌐
The Python Coding Stack
thepythoncodingstack.com › the python coding stack › a slicing story
A Slicing Story - by Stephen Gruppetta
June 25, 2024 - Slices create copies when dealing with lists, strings, tuples, and other built-in data types. However, this behaviour is not guaranteed by slicing, as you've seen in the case of NumPy arrays.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-slicing-multi-dimensional-arrays
Python Slicing Multi-Dimensional Arrays - GeeksforGeeks
2 weeks ago - This produces a new 2-D array containing the last column values from every matrix. Slices can be used not only for reading data but also for updating multiple values at once. Python · import numpy as np matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matrix[0:2, 0:2] = 0 print(matrix) Output ·
🌐
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....
🌐
Reddit
reddit.com › r/python › a comprehensive guide to slicing in python
r/Python on Reddit: A Comprehensive Guide to Slicing in Python
February 1, 2022 - I've always found array slicing in python to be very powerful and useful, and a thing i wish more languages had. For my common use case (dealing with text) it's very fast to code something up. ... I'm very new to Python and one thing I find confusing and unintuitive is that some things, like slices, start counting at 0 but other things like groups in regular expressions start counting at 1.
🌐
NumPy
numpy.org › doc › stable › user › basics.indexing.html
Indexing on ndarrays — NumPy v2.5 Manual
The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index). Some useful concepts to remember include: The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step (\(k\neq0\)).
🌐
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.
🌐
StrataScratch
stratascratch.com › blog › numpy-array-slicing-in-python
NumPy Array Slicing in Python - StrataScratch
March 1, 2024 - 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/pythonlearning › slicing 2d numpy arrays
r/PythonLearning on Reddit: Slicing 2D Numpy arrays
August 11, 2024 -

So,here I come again 🤣

I don't get slicing in 2D..

In my lesson,I was taught that using this

d[1:2,1] 

means the 2nd element from the last two rows,and 2nd element from 1st column should be sliced..but when I use it I get only one element.Did I do something wrong?Can some of you awesome people hook me up with an explanation?

Here's some code for your palates:

a=[[1,2,3],[4,5,6],[7,8,9]]
import numpy as np
d=np.array(a)
d[1:2,1]
🌐
Python Central
pythoncentral.io › how-to-slice-listsarrays-and-tuples-in-python
How to Slice Lists/Arrays and Tuples in Python | Python Central
July 18, 2022 - A guide to slicing Python lists/arrays and Tuples, using multiple forms of syntax. We can use the short form of Python slicing, or the slice method.
🌐
DataCamp
campus.datacamp.com › courses › introduction-to-numpy › selecting-and-updating-data
Indexing and slicing arrays | Python
Slicing extracts a subset of data based on given indices from one array and creates a new array with the sliced data. To slice, provide a start and stop value, separated by a colon and enclosed in square brackets.
🌐
Shishirkant
shishirkant.com › array-indexing-and-slicing-in-python
Array Indexing and Slicing in Python – Shishir Kant Singh
1. Basic Slicing and indexing : Consider the syntax x[obj] where x is the array and obj is the index. Slice object is the index in case of basic slicing.
🌐
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 ...
🌐
Medium
medium.com › @timothyjosephcw › what-is-python-slicing-and-how-does-slicing-in-python-work-2788632c5ba0
What is Python Slicing and How Does Slicing in Python Work? | by timothy joseph | Medium
August 22, 2024 - Python my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Accessing elements from index 2 to 5 (exclusive) sublist = my_list[2:5] print(sublist) # Output: [2, 3, 4] # Accessing elements from the beginning to index 4 (exclusive) sublist = my_list[:4] print(sublist) # Output: [0, 1, 2, 3] # Accessing elements from index 3 to the end sublist = my_list[3:] print(sublist) # Output: [3, 4, 5, 6, 7, 8, 9] # Accessing every other element sublist = my_list[::2] print(sublist) # Output: [0, 2, 4, 6, 8] # Reversing the list reversed_list = my_list[::-1] print(reversed_list) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]