r/PythonLearning • • 4d ago

i am stuck with the range function

sorry but i am gonna crash out because of the range function i cant understand it well to use it this is driving me crazy any one could give me a video explaining everything i dont mind it being an hour long

8 Upvotes

33 comments sorted by

View all comments

2

u/tb5841 4d ago

range(n) produces an object.

If you put in 5, for example, range(5) produces the numbers 0, 1, 2, 3, 4.

It starts at 0 by default, goes up by 1 each time by default, and goes up to just before the number you put in.

You can change where it starts, and what it goes up by each time, but don't worry about that for now.

There are two things that make it seem confusing. One is that you most often see it in 'for' loops, and if you're not happy with loops yet then that won't make sense. The other is that the return value of the range() function, that contains the numbers 0, 1, 2, 3, 4, is a type of object you haven't come across yet.

Don't find a video. Open Python, type stuff, and see if you can work out what's happening. Avoid anything with a 'for' loop for now. Some stuff worth trying out:

r = range(5)

print(r)

print(list(r))

print(3 in r)

print(5 in r)

print(set(r))

...etc.