Sobes.tech
Intern

What is a range in the context of Python?

sobes.tech AI

Answer from AI

A range in Python is a sequence object that represents an immutable sequence of numbers and is often used for iteration in for loops.

# Examples of creating range objects
r1 = range(5)          # From 0 to 4 (excluding 5)
r2 = range(1, 6)       # From 1 to 5 (excluding 6)
r3 = range(0, 10, 2)   # From 0 to 9 with step 2 (0, 2, 4, 6, 8)

Main properties:

  • Lazy evaluation: Elements are generated on demand, saving memory, especially for large ranges.
  • Immutable: Once created, a range object cannot be changed.
  • Memory-efficient: Stores only start, stop, and step, not all elements.

Usage in loops:

for i in range(5):
    print(i) # Will print 0, 1, 2, 3, 4

my_list = [10, 20, 30, 40]
for i in range(len(my_list)):
    print(f"Element at index {i}: {my_list[i]}")

The range() function accepts up to three arguments: range(stop), range(start, stop), range(start, stop, step).

  • start: Starting value (inclusive). Defaults to 0.
  • stop: End value (exclusive). Required.
  • step: Increment. Defaults to 1. Can be negative.

Example with negative step:

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