List Slicing

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

It takes two parameters: the starting index and the ending index (optional). It returns a new list containing the extracted portion.

Let's perform such operations on the list ['cat', 'dog', 'fish', 'turtle', 'parrot']. Its structure is the following:

list-slicing-structure

Single argument slicing

Positive argument slicing

Output:

In this example, elements[2:] skips the first 2 elements of the list - 'cat' and 'dog'.

The remaining part of the list (starting from the 3rd element) is extracted - ['fish', 'turtle', 'parrot'].

Negative argument slicing

Negative indexes count the list elements in reverse.

positive-and-negative-argument-slicing

Output:

In this example, elements[-3:] extracts only the last 3 elements of the list - 'fish', 'turtle', and 'parrot'.

Two arguments slicing

Positive arguments slicing

Output:

In this example, elements[1:3] skips the first element of the list - 'cat'.

Afterwards, it takes the rest of the list until it reaches the 3rd element - 'dog' and 'fish'.

Negative arguments slicing

Output:

In this example, elements[-4:-2] starts slicing at the 4th element counting backwards and ends before the 2nd element counting backwards.

Mixed arguments slicing

Both positive and negative arguments can be specified.

Output:

In this example, elements[1:-1] starts after the first element and ends before the last element.

Invalid cases

An invalid case simply returns an empty list. In such cases, the slicing start argument position is after the slicing end.

Example of valid and invalid cases:

Output:

Another invalid slicing case is specifying a starting argument that's beyond the list's bounds:

Output:

Three arguments slicing

The third argumen allows you to specify an additional step (also known as the stride) to skip characters in the range while slicing.

Output:

In this example 2 specifies that every 2nd element of the list must be extracted.

It can be combined with the other arguments to slice only in a certain range and with specific step:

Output:

In this case the first argument (1) skips the first element - 'cat'.

The second argument (-1) skips the last one symbol - 'rabbit'.

The third argument takes every 2nd symbol of the sliced list (['dog', 'turtle', 'hamster']) - s, r, h and e.