Skip to content
Fix Code Error

Understanding slice notation

March 13, 2021 by Code Error
Posted By: Simon

I need a good explanation (references are a plus) on Python’s slice notation.

To me, this notation needs a bit of picking up.

It looks extremely powerful, but I haven’t quite got my head around it.

Solution

It’s pretty simple really:

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.

Relation to slice() object

The slicing operator [] is actually being used in the above code with a slice() object using the : notation (which is only valid within []), 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, similarly 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.

Answered By: Greg Hewgill

Related Articles

  • Can't install via pip because of egg_info error
  • Form field border-radius is not working only on the…
  • How do I merge two dictionaries in a single…
  • What's the difference between eval, exec, and compile?
  • How does PHP 'foreach' actually work?
  • What is your most productive shortcut with Vim?
  • What is the copy-and-swap idiom?
  • Ukkonen's suffix tree algorithm in plain English
  • For-each over an array in JavaScript
  • Maximum XOR With an Element From Array | Leetcode
  • Iterator invalidation rules
  • Why does the function named "traverse" not work on my code?
  • How to update Python?
  • SOAP vs REST (differences)
  • In plain English, what does "git reset" do?
  • Memcached vs. Redis?
  • How to add "on delete cascade" constraints?
  • Getting started with Haskell
  • data.table vs dplyr: can one do something well the…
  • How would I be able to multiple select and pass data…
  • Install pip in docker
  • What does this symbol mean in JavaScript?
  • How to generate a random string of a fixed length in Go?
  • Smart way to truncate long strings
  • Why does C++ code for testing the Collatz conjecture…
  • Head pointer not accessible when creating a method…
  • Callback functions in C++
  • List changes unexpectedly after assignment. How do I…
  • Programmatically Lighten or Darken a hex color (or…
  • How to make onClick card to move to another page in react
  • How can I reconcile detached HEAD with master/origin?
  • How can I access and process nested objects, arrays or JSON?
  • What does T&& (double ampersand) mean in C++11?
  • How do I parse command line arguments in Bash?
  • How to take column-slices of dataframe in pandas
  • Ways to save Backbone.js model data?
  • C, How to Remove Element From Queue?
  • The definitive guide to form-based website authentication
  • Backbone.js - Should nested Views maintain…
  • Android REST client, Sample?
  • How do I correctly clone a JavaScript object?
  • Dynamically allocating an array of objects
  • Trouble with qsort with key/value structs in a btree
  • Copy a variable's value into another
  • Usage of __slots__?
  • Are dictionaries ordered in Python 3.6+?
  • How to filter a RecyclerView with a SearchView
  • How does origin/HEAD get set?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • When dealing with Localizable.stringsdict, why…
  • Relative imports for the billionth time
  • What's the difference between "git reset" and "git…
  • NSPhotoLibraryUsageDescription key must be present…
  • Reference - What does this regex mean?
  • What are type hints in Python 3.5?
  • What is The Rule of Three?
  • Start redis-server with config file
  • Resource-efficient finding ONE possible combinations…
  • Remove similar tuple from dictionary of tuples
  • What does Ruby have that Python doesn't, and vice versa?
  • When is assembly faster than C?
  • key_load_public: invalid format
  • A function in C that adds a node at the end of a…
  • MSBuild doesn't copy references (DLL files) if using…
  • Problems Installing CRA & NextJS from NPM…
  • What does "dereferencing" a pointer mean?
  • Fastest way to iterate over all the chars in a String
  • Database development mistakes made by application developers
  • ember-data: Loading hasMany association on demand
  • JavaScript gives NaN error on the page but variable…
  • How to handle Vue 2 memory usage for large data (~50…
  • Click button copy to clipboard using jQuery
  • Pandas Merging 101
  • Simple linked list in C++
  • Why is "1000000000000000 in range(1000000000000001)"…
  • How do you sign a Certificate Signing Request with…
  • multiple login routes using ember-cli-simple-auth
  • Difference between partition key, composite key and…
  • How to count the number of set bits in a 32-bit integer?
  • Install opencv for Python 3.3
  • How do I include certain conditions in SQL Count
  • What are the nuances of scope prototypal /…
  • Design DFA accepting binary strings divisible by a…
  • How can I manually compile a svelte component down…
  • How can I convert the "arguments" object to an array…
  • Programmatically generate url from path and params
  • What is move semantics?
  • Conventions required of RESTful JSON API to be…
  • Understanding REST: Verbs, error codes, and authentication
  • Keras Sequential API is replacing every layer with…
  • Change a Git remote HEAD to point to something…
  • Questions every good .NET developer should be able…
  • JavaScript hashmap equivalent
  • invalid instantiation of template by compiler giving error
  • pip cannot install anything
  • Extract list element from column of dataframe using R
  • Implement LRU cache with using…
  • Add Expires headers
  • Make div fill remaining space along the main axis in flexbox
  • Logging best practices

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

What are the -Xms and -Xmx parameters when starting JVM?

Next Post:

How to print without newline or space?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error