python-slices

How to use Slices in Python

  • 5 min

Slices in Python are a very useful tool that allows us to extract portions of sequences of elements (like lists, tuples, or strings) with very little code.

Slices allow us to work with specific fragments of a sequence, without having to modify or iterate over the entire sequence.

The basic syntax for creating a slice in Python is as follows:

sequence[start:end:step]
Copied!
  • start: Index where the slice begins (included)
  • end: Index where the slice ends (not included)
  • step: Step size or increment between slice elements (optional)

Special Considerations

Modifying Values with Slices

Slices can also be used to modify values in a sequence.

fruits = ["apple", "banana", "cherry", "date", "grape"]

fruits[1:3] = ["pear", "orange"]  # Replaces "banana" and "cherry" with "pear" and "orange"
Copied!

In this case,

  • fruits[1:3] selects the elements "banana" and "cherry"
  • Replaces them with "pear" and "orange".

Practical Examples

Let’s assume we have a list of numbers:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copied!

Now, let’s see how Slicing behaves with different combinations of start, stop, and step: