What is slicing in Python?

Slicing enables the extraction of a designated range of elements from arrays, lists, strings, or tuples using the syntax [start : stop : step]. Here,

  • start denotes the beginning or starting index,
  • stop indicates the ending index, and
  • step determines the interval between elements in the specified range.

The default values for start is 0, stop is the length of the array, and step is 1. You can also use negative values for start and stop to count from the end of the array instead of the beginning.

You can slice any array-like object, such as a list, tuple, or string. Here are some examples of how you can use slicing with these objects:

Slicing with start and stop:

The start and stop indices determine the range of elements that will be included in the slice.
These indices are inclusive for start and exclusive for stop. For example:

Note: Indexing in Python starts from index 0 instead of 1.

Slicing with step:

The step value determines the interval between elements that will be included in the slice. If step is greater than 1, it will skip over elements. If step is negative, it will include elements in reverse order. For example:

Note: Indexing in Python starts from index 0 instead of 1.

Slicing with negative indexes:

If start or stop are negative, they will be counted from the end of the array instead of the beginning. For example:

Note: Indexing in Python starts from index 0 instead of 1.

If there are fewer elements in the array than requested in the slice, Python will return an empty list or string instead of an error. This is a convenient feature, but it’s important to be aware of it in case you want to handle such cases differently.