What about range with three arguments?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 24 2025
0109

In Python, the range function can take three arguments: start, stop, and step. The syntax is as follows:

range(start, stop, step)

Explanation of Each Argument

  1. start:

    • The value at which the sequence begins (inclusive).
    • Default is 0 if not specified.
  2. stop:

    • The value at which the sequence ends (exclusive).
    • This argument is required.
  3. step:

    • The difference between each consecutive number in the sequence.
    • Default is 1 if not specified.
    • Can be negative to generate a decreasing sequence.

Examples

  1. Basic Example:

    print(list(range(1, 10, 2)))  # Output: [1, 3, 5, 7, 9]
    • Starts at 1, ends before 10, and increments by 2.
  2. Negative Step:

    print(list(range(10, 0, -2)))  # Output: [10, 8, 6, 4, 2]
    • Starts at 10, ends before 0, and decrements by 2.
  3. Default Step:

    print(list(range(5)))  # Output: [0, 1, 2, 3, 4]
    • Starts at 0, ends before 5, with a default step of 1.

Summary

  • The three-argument form of range allows for more control over the sequence of numbers generated, enabling you to specify where to start, where to stop, and how to increment or decrement the values.

If you have any further questions or need clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!