1

If range(0, 3) returns the sequence 0, 1, 2

then why can't I simply print this sequence using the following code:

x = range (0, 3)
print(x)

Why do I need to use a for loop to do so?

x = range (0, 3)
for i in x:
    print(i)

How do I understand how the range function generates the sequence and stores it, making a iterating function necessary to access all the numbers in the sequence.

Anonymouse
  • 147
  • 1
  • 8
  • Might want to take a look at [this answer](https://stackoverflow.com/a/43464225/9374673) as well about printing ranges. Doesn't quite answer this specific question but worth having a look. – Mihai Chelaru Feb 26 '21 at 15:32

3 Answers3

4

This is precisely beacause range is a generator; it doesn't return a list, it returns an iterable object whose next() method returns another item from the list it represents.

Of course, you can always

print(list(range(0, 3))

or

print(*range(0, 3))
tripleee
  • 139,311
  • 24
  • 207
  • 268
1

range is a generator function not a list. To get values from a generator you need to iterate through the generator calling for the next value. A for loop does that.

Kenan
  • 10,163
  • 8
  • 32
  • 47
1

range(0, 3) is a generator so the values are not actually produced until you loop over it.

You could cast it to a list to print:

x = range(0, 3)
print(list(x))
D Hudson
  • 777
  • 2
  • 9