What is use of slicing in Python?

In Python, slicing is a technique used to extract a portion of a sequence, such as a string, list, or tuple.

The slice notation is expressed using square brackets []. The general syntax for slicing is sequence[start:stop:step], where start is the index of the first item to be included in the slice, stop is the index of the first item to be excluded from the slice, and step is the optional increment between items in the slice.

text = "Hello, World!" substring = text[0:5]  # extracts "Hello"

Extracting a substring from a string

my_list = [1, 2, 3, 4, 5] sublist = my_list[1:4]  # extracts [2, 3, 4]

Extracting a sublist from a list

text = "Hello, World!" reverse_text = text[::-1]  # extracts "!dlroW ,olleH"

Reversing a sequence

my_list = [1, 2, 3, 4, 5] skip_items = my_list[::2]  # extracts [1, 3, 5]

Skipping items in a sequence