-5

How to get expected answer [0, 1, 2, 3] using the range function?

I tried this Python code:

print(range(4)), 

result:

range(0,4)

The result is different from online playgrounds:

result 01: range(0,4) 
result 02: [0, 1, 2, 3]
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Yee Leong
  • 3
  • 2

2 Answers2

1

The general syntax of range function:

range(start, stop, step)

start : Numerical index, at which position to start(optional)

stop : Index you go upto but not include the number(position to end)(required)

step: Incremental step size(optional)

Examples

x = range(0, 6)
for n in x:
  print(n) //output: 0 1 2 3 4 5

In your case you need a list containing the integers so as @Green Cloak Guy said you should use list(range(4))

DPS
  • 943
  • 11
  • 22
0

do list(range(4)).

The range() function returns a generator (only produces one value at a time). You have to convert that generator to a list.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • 1
    [Note on range object not being a generator](https://stackoverflow.com/questions/13092267/if-range-is-a-generator-in-python-3-3-why-can-i-not-call-next-on-a-range) but the answer is generally correct. Just an alert since there can be confusion in attempts to use range as a generator (i.e. no next). – DarrylG Oct 23 '19 at 03:29