Remember
range() represents an arithmetic sequence of integers. Its stop value is excluded, and it does not store every integer as a list.
range() represents an arithmetic sequence of integers. Its stop value is excluded, and it does not store every integer as a list.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
numbers = range(3)
print(list(numbers))Top-level scope
range(0, 3)range() represents an arithmetic sequence of integers. Its stop value is excluded, and it does not store every integer as a list.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
numbers = range(3)
print(list(numbers))
|
v
DISPLAYED RESULT
[0, 1, 2]
FINAL BINDINGS
numbers --> object 1 (range)
object 1: range(0, 3)Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
numbers = range(3)
print(list(numbers))Top-level scope
range(0, 3)The example has finished. Compare the final output with the values and references above.
[0, 1, 2]
What do you expect this program to print?
numbers = range(3)
print(list(numbers))range() FunctionThe range() function in Python is used to generate a sequence of numbers. It's commonly used in for loops to repeat a block of code a specific number of times.
range(stop)
range(start, stop)
range(start, stop, step)
start (optional) – The starting number of the sequence. Defaults to 0.stop – The number at which to stop (not included).step (optional) – The difference between each number in the sequence. Defaults to 1.An immutable sequence type of numbers.
for i in range(5):
print(i)
0
1
2
3
4
for i in range(2, 6):
print(i)
2
3
4
5
for i in range(1, 10, 2):
print(i)
1
3
5
7
9
for i in range(5, 0, -1):
print(i)
5
4
3
2
1
print(list(range(1, 6)))
[1, 2, 3, 4, 5]
Using list() helps you visualize the numbers generated by range().
stop is exclusive (not included)ValueErrorrange() returns a list – it returns a special range objectrange() is often used in loop-based questions. Practice customizing start, stop, and step to write optimized code.
range() generates numbers from start to stop - 1list() if you want to view or print the sequencePrint all even numbers between 10 and 30 using range().
for i in range(10, 31, 2):
print(i)
10
12
14
16
18
20
22
24
26
28
30
Connect what you noticed in the example with the idea below.
range() represents an arithmetic sequence of integers. Its stop value is excluded, and it does not store every integer as a list.
range(n) includes the stop value n.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.