Range Function

Generating sequences with range()

Interview Relevant: Common in loops

Range Function

Generate sequences of numbers.

Code Examples

Using range() for sequences.

python
1# range(stop)
2list(range(5))       # [0, 1, 2, 3, 4]
3
4# range(start, stop)
5list(range(2, 7))    # [2, 3, 4, 5, 6]
6
7# range(start, stop, step)
8list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
9
10# Negative step (countdown)
11list(range(5, 0, -1)) # [5, 4, 3, 2, 1]
12
13# range is lazy (memory efficient)
14r = range(1000000)
15len(r)        # 1000000
16999999 in r   # True (fast!)
17
18# Convert to list if needed
19numbers = list(range(10))
20
21# Common patterns
22for i in range(len(lst)):  # Less Pythonic
23    print(lst[i])
24
25for i, val in enumerate(lst):  # More Pythonic
26    print(i, val)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In