Range

 In Python, range is a built-in function that is used to generate a sequence of numbers. It is commonly used in for loops to iterate a specific number of times or to create sequences of numbers. The basic syntax of the range function is as follows:

range(stop) range(start, stop) range(start, stop, step)
  • start (optional): The starting value of the sequence. If not specified, it defaults to 0.
  • stop: The exclusive upper limit of the sequence. The sequence will stop before reaching this value.
  • step (optional): The step or the difference between each number in the sequence. If not specified, it defaults to 1.

Here are a few examples to illustrate the usage of the range function:

  1. Using range with a Stop Value:

    for i in range(5): print(i)

    Output:

    In this example, range(5) generates a sequence of numbers from 0 to 4.

  2. Using range with Start and Stop Values:

    for i in range(2, 8): print(i)

    Output:

    2 3 4 5 6 7

    Here, range(2, 8) generates a sequence from 2 to 7.

  3. Using range with Start, Stop, and Step Values:

    for i in range(1, 10, 2): print(i)

    Output:

    In this case, range(1, 10, 2) generates a sequence with a step of 2 between numbers.

  4. Creating a List with range:

    numbers = list(range(3, 15, 3)) print(numbers)

    Output:

    [3, 6, 9, 12]

    Here, range(3, 15, 3) is used to create a list of numbers with a step of 3.

The range function is useful when you need to iterate over a sequence of numbers or when you want to create a list of numbers with a specific pattern. Keep in mind that the range function does not create a list directly; it produces a range object. If you need a list, you can convert it using the list() constructor, as shown in the last example.

Comments