Language: EN

uso-de-range-en-python

Using range in Python

The range() function in Python generates an immutable sequence of integers in a specific range.

Syntax

The general syntax of range() is:

range(start, stop, step)
  • start: Initial value of the sequence (inclusive). If not specified, it defaults to 0.
  • stop: Final value of the sequence (exclusive). This value is never part of the generated sequence.
  • step: Increment between each number in the sequence. If not specified, it defaults to 1.

The range() function returns a range object, which is memory efficient and suitable for generating large sequences of numbers.

range() is useful in contexts where you need to generate “fixed” numerical sequences that do not vary (for example in for loops, mathematical operations, and data manipulation).

Basic Examples

Basic Usage

In this example, we use range to generate a sequence of numbers from 0 to 4, where the specified final value is not included in the sequence.

# Generate a sequence from 0 to 4 (exclusive)
for i in range(5):
    print(i)
# Output: 0, 1, 2, 3, 4

Specifying Start and Stop

Here, range is used to generate a sequence that starts at 2 and ends at 8 (exclusive), showing how both the start and stop of the sequence can be defined.

# Generate a sequence from 2 to 8 (exclusive)
for i in range(2, 9):
    print(i)
# Output: 2, 3, 4, 5, 6, 7, 8

Specifying Step

In this example, it shows how to generate a sequence that starts at 1 and ends at 10, with an increment of 2 at each step.

# Generate a sequence from 1 to 10 with a step of 2
for i in range(1, 11, 2):
    print(i)
# Output: 1, 3, 5, 7, 9

Iterating in Reverse Order

This example demonstrates how to use range to iterate in reverse order, starting from 10 and ending at 1.

# Iterate in reverse order
for i in range(10, 0, -1):
    print(i)
# Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Practical Examples