Slices

This lesson describes some important concepts about slices, i.e., how to use, declare and initialize them.

We'll cover the following

Concept

A slice is a reference to a contiguous segment (section) of an array (which we will call the underlying array, and which is usually anonymous), so a slice is a reference type (more like the array type in C/C++, or the list type in Python). This section can be the entire array or a subset of the items indicated by a start and an end index (the item at the end index is not included in the slice). Slices provide a dynamic window to the underlying array.

A slice in memory is a structure with 3 fields:

  • a pointer to the underlying array
  • the length of the slice
  • the capacity of the slice

Slices are indexable and have a length given by the len() function. The slice-index of a given item can be less than the index of the same element in the underlying array. Unlike an array, the length of a slice can change during the execution of the code, minimally 0 and maximally the length of the underlying array, which means a slice is a variable-length array.

The built-in capacity function cap() of a slice is a measure of how long a slice can become. It is the length of the slice + the length of the array beyond the slice. If s is a slice, cap is the size of the array from s[0] to the end of the array. A slice’s length can never exceed its capacity, so the following statement is always true for a slice s:

0 <= len(s) <= cap(s)

This is illustrated in the following figure, where the slice x has a capacity and length of 5. Slice y, on the other hand, is of length 4 and capacity 4. The y slice takes its value from slice x. The slice y is equal to x[1:5] and contains the elements 3, 5, 7 and 11.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy