What does range() return in Python 3, and is it a list?
range() returns a lazy range object, not a list. It stores only start, stop and step, so range(10**9) takes tiny memory, supports indexing, len() and the in operator, and produces numbers only when asked.
Explain it simply
A list of one crore numbers is like printing one crore ticket stubs in advance. A range is like the rule "start at 0, go up by 1 until 10 million": a few words on a card, and any ticket can be worked out on demand.
The stop value is excluded, and the step can be negative.
Example
r = range(2, 20, 4)
print(r) # Output: range(2, 20, 4)
print(list(r)) # Output: [2, 6, 10, 14, 18]
print(len(r)) # Output: 5
print(r[2]) # Output: 10
print(14 in r) # Output: True
print(list(range(5, 0, -2))) # Output: [5, 3, 1]
print(list(range(3, 3))) # Output: []What to say in the interview
"In Python 3, range is an immutable sequence type that computes values lazily from start, stop and step, so memory is constant however large it is. It supports len, indexing, slicing and fast membership tests for ints. In Python 2, range built a real list, which is why xrange existed."
Common mistakes
- Expecting the stop value to be included.
- Printing
range(5)and expecting to see[0, 1, 2, 3, 4]; wrap it inlist().