Understanding slicing

In Python, slicing refers to taking a subset of a sequence (such as a list, string, or tuple) by using indices to specify the start and end points of the slice. The slice is taken from the start index and includes all the elements up to but not including the end index.

Here's an example of how to use slicing to get a sublist from a list:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[3:7])

In this example, the slice numbers[3:7] starts at index 3 and includes all the elements up to but not including index 7. So the result is a sublist containing the elements at indices 3, 4, 5, and 6.

Watch a course Python - The Practical Guide

You can also use negative indices to slice a sequence. A negative index counts backwards from the end of the sequence, so -1 refers to the last element, -2 refers to the second to last element, and so on.

For example:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[-3:])

This slice starts at index -3 (the third to last element) and includes all the remaining elements, so the result is a sublist containing the elements at indices 7, 8, and 9.

You can also specify a step size for the slice by using the step parameter. The step size specifies how many indices to skip between elements. For example:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[1:8:2])

This slice starts at index 1 and includes all the elements up to but not including index 8, skipping over elements with a step size of 2. The result is a sublist containing the elements at indices 1, 3, 5, and 7.

I hope this helps! Let me know if you have any questions.