Language: EN

python-slices

How to use Slices in Python

The “slices” in Python are a very useful tool that allows us to extract portions of sequences of elements (such as 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 sequence.

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

sequence[start:end:step]
  • start: Index where the slice begins (inclusive)
  • end: Index where the slice ends (exclusive)
  • step: Size of the step or increment between elements of the slice (optional)

Special Considerations

Omitting Values

We can omit one, several, or even all parameters of the slice. Each omission will behave differently.

If we do not specify:

  • The start, the slice will begin from the first element
  • The end, the slice will end at the last element
  • The step, the slice will use a step of 1
first_except_three = numbers[3:]  # Extracts elements from 3 to the end
first_three = numbers[:3]  # Extracts the first three elements

See the examples below to fully understand the concepts 👇

Using Negative Indices

Python allows the use of negative indices to refer to elements relative to the end of the sequence (instead of from the beginning).

It seems a bit complicated and can be a little confusing at first. But basically,

last_three = numbers[-3:]  # Extracts the last three elements
first_except_three = numbers[:-3]  # Extracts elements, except the last three

On the other hand, if the step is negative, the slice traverses the sequence in reverse order.

Again, see the examples below to fully understand the concepts 👇

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"

In this case,

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

Practical Examples

Suppose we have a list of numbers:

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

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

:::::::