Sobes.tech
Junior — Middle

Can you describe the main features of the range function in Python?

sobes.tech AI

Answer from AI

The range function in Python is used to generate a sequence of numbers and is often used in for loops. Main features:

  • Returns an iterator object that generates numbers within a specified range.
  • Can accept from one to three arguments:
    • range(stop) — numbers from 0 to stop - 1.
    • range(start, stop) — numbers from start to stop - 1.
    • range(start, stop, step) — numbers from start to stop - 1 with a step of step.
  • Supports positive and negative steps.
  • Lazy — numbers are generated as needed, saving memory.

Example:

for i in range(2, 10, 2):
    print(i)
# Output: 2 4 6 8

range is often used for iteration with indices or creating lists of numbers.