What is slicing in Python?

Slicing allows you to extract a specific range of elements from an array, list, string, or tuple. The syntax for slicing is [start:stop:step], where start is the starting index of the range,stop is the ending index, and step is the number of elements to skip between each element in the 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. For example:

    • my_list = [1, 2, 3, 4, 5]
    • my_tuple = (6, 7, 8, 9, 10)
    • my_string = "abcdef"
  • 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:

    • my_list[1:3] returns [2, 3]
    • my_tuple[:3] returns (6, 7, 8)
    • my_string[2:] returns "cdef"
  • 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:

    • my_list[::2] returns [1, 3, 5]
    • my_tuple[::-1] returns (10, 9, 8, 7, 6)
    • my_string[3:0:-1] returns "dca"
  • If “start” or “stop” are negative, they will be counted from the end of the array. For example:

    • my_list[-2:] returns [4, 5]
    • my_tuple[:-3] returns (6, 7)
    • my_string[-3:-1] returns "de"
  • 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.

Example