uso-de-range-en-python

Using range in Python

  • 3 min

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

Syntax

The general syntax of range() is:

range(start, stop, step)
Copied!
  • 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 an object of type range, which is memory efficient and suitable for generating large number sequences.

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

Basic Examples

Basic Usage

In this example, we use range to generate a sequence of numbers from 0 to 4, where the specified stop 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
Copied!

Specifying Start and Stop

Here, range is used to generate a sequence starting at 2 and ending at 8 (exclusive), showing how you can define both the start and stop of the sequence.

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

Specifying Step

This example shows how to generate a sequence starting at 1 and ending 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
Copied!

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
Copied!

Practical Examples