List Slicing

List slicing allows you to extract a portion of a List.

It takes two parameters: the starting index and how many elements must be sliced. It returns a new List containing the extracted portion.

Sublist Between Specified Indices

Output:

In this example, animals.GetRange(1, 3) skips the first element of the List - 'cat'.

Afterwards it takes the next 3 elements - 'dog', 'fish', and 'turtle'.

Excluding the last couple of elements:

Output:

This example takes all elements (starting from index 0) and excludes the last 2 elements specified by colors.Count - 2.

In this case, colors has 7 elements. So colors.Count - 2 is the same as 7 - 2 which is 5.

Selecting the last couple of elements:

Output:

This is the same as:

Output:

Removing Sublist

A sublist inside a List can be removed.

Output:

RemoveRange(2, 3) selects the following sublist - [blue, pink, gray]

The RemoveRange function removes the elements of the sublist.

After removing the sublist elements, the remaining elements are - [red, green, purple, white].

Invalid cases

Invalid cases result in an error. Such cases involve accessing an index outside of the List bounds.

Example:

In this example, 15 is outside of the list bounds.

Another case for an index being outside of the list bounds is using negative indexes such as colors.GetRange(0, -3);.