search

What is slicing in Python and how to use it?

Slicing in Python is a feature that allows you to extract a portion of a sequence (such as a list, tuple, or string) and create a new sequence from it. The portion of the sequence that you extract is known as a "slice".

In Python, you can slice a sequence using the following syntax:

sequence[start:stop:step]

where:

**start** is the index of the first item in the slice (inclusive). If **start** is omitted, it defaults to 0.

**stop** is the index of the first item after the last item in the slice (exclusive). If **stop** is omitted, it defaults to the length of the sequence.

**step** is the number of items to skip between items in the slice. If **step** is omitted, it defaults to 1.

For example:

# Slicing a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[3:7])  # Output: [4, 5, 6, 7]
print(numbers[:7:2])  # Output: [1, 3, 5, 7]
print(numbers[7:])  # Output: [8, 9, 10]

# Slicing a string
name = "John Doe"
print(name[:4])  # Output: "John"
print(name[5:])  # Output: "Doe"

Note that slicing a sequence creates a new sequence that is a shallow copy of the original sequence. This means that if the original sequence contains mutable objects, modifying an item in the sliced sequence will also modify the corresponding item in the original sequence.

Related Questions You Might Be Interested