Range

range() in Python

The range() function in Python is used to generate a sequence of numbers. It's commonly utilized in for loops to iterate a fixed number of times efficiently.


Forms of the range() Function

The range() function can be used in three forms:

  1. range(stop)
    Generates numbers from 0 up to, but not including, stop.

  2. range(start, stop)
    Generates numbers from start up to, but not including, stop.

  3. range(start, stop, step)
    Generates numbers from start up to, but not including, stop, incrementing by step (which can be positive or negative).


1. range(stop)

When using a single argument, the sequence starts at 0 and ends at stop - 1.

Example:

# Print the first 6 integers for i in range(6): print(i, end=" ")

Output:

0 1 2 3 4 5

2. range(start, stop)

When two arguments are given, the sequence starts from start and ends at stop - 1.

Example:

# Print numbers from 5 to 19 for i in range(5, 20): print(i, end=" ")

Output:

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

3. range(start, stop, step)

With three arguments, range() defines the start, end, and step between values.

Example:

# Print even numbers from 0 to 8 for i in range(0, 10, 2): print(i, end=" ")

Output:

0 2 4 6 8

Additional Examples

Example 1: Range with Negative Step

# Count backwards from 20 to 12 by -2 for i in range(20, 10, -2): print(i, end=" ")

Output:

20 18 16 14 12

Example 2: Negative Step with Different Interval

# Count backwards from 20 to 11 by -3 for i in range(20, 10, -3): print(i, end=" ")

Output:

20 17 14 1

Popular Posts