How do slicing steps and negative indices work?

In Python, slicing allows you to retrieve a subset of elements from a list, string, or tuple. The syntax for slicing is as follows:

sequence[start:stop:step]

Where:

  • start: The index at which to start the slice (inclusive).
  • stop: The index at which to end the slice (exclusive).
  • step: The increment between each index in the slice.

Negative indices in Python count from the end of the sequence. For example, -1 refers to the last element, -2 refers to the second-to-last, and so on. This feature allows for more flexible slicing of sequences.

Here’s an example demonstrating slicing with steps and negative indices:

# Sample list numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Slicing examples slice1 = numbers[2:8:2] # Output: [2, 4, 6] slice2 = numbers[-3:] # Output: [7, 8, 9] slice3 = numbers[::-1] # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

slicing negative indices Python slicing Python lists Python examples