What does `step` in slicing do?

QuestionsQuestions8 SkillsProDec, 23 2025
0149

Great question! In Python slicing, the step value determines the increment between each index in the slice.

The full slicing syntax is: list[start:stop:step]

Think of it like taking a walk through the list: start is where you begin, stop is where you finish (exclusive), and step is how many "steps" you take at once.

How it works:

  1. Default Step (1):
    If you don't provide a step, it defaults to 1, meaning it takes every single element.

    nums = [10, 20, 30, 40, 50]
    print(nums[0:4:1]) # Output: [10, 20, 30, 40]
  2. Skipping Elements (step > 1):
    If you set the step to 2, it takes the first element, skips one, takes the next, and so on.

    nums = [0, 1, 2, 3, 4, 5, 6]
    # Start at 0, end at 6, take every 2nd element
    print(nums[0:6:2]) # Output: [0, 2, 4]
  3. Going Backwards (negative step):
    If the step is negative, Python moves from right to left. This is a very popular way to reverse a list!

    nums = [1, 2, 3, 4, 5]
    print(nums[::-1]) # Output: [5, 4, 3, 2, 1]

Summary:

  • step=1: Every item (default).
  • step=2: Every other item (alternating).
  • step=-1: Every item in reverse order.

You can try adding print(furniture[::2]) to your step1_access.py file to see it skip every second item in your furniture list! Is there anything else about slicing you'd like to clarify?

0 Comments

no data
Be the first to share your comment!