r/learnpython • • Oct 09 '20

Understanding the For Loop

Hey All,

I'm having the hardest time understanding for loops in Python.

Could someone explain what is happening in this example? I see we have a variable v. I somewhat understand that "range" is built into Python. I don't understand the output.

for v in range(3, 10, 3):
    print(v)

Output:

3

6

9

I keep seeing examples online but they lose me every time. Thank you in advance.

-------------------------------------------------

*Edit Thanks to everyone who replied. My misunderstanding was not knowing what range was fully doing.

range(start, stop, step)

366 Upvotes

62 comments sorted by

View all comments

Show parent comments

4

u/stormsnake Oct 09 '20

You can take a look in the python interactive interpreter, although in this case there's a catch:

>>> range(3, 10, 3)
range(3, 10, 3)  <-- this is an annoying representation of the return value of the range function

>>> list(range(3, 10, 3))  <-- here's how to preview a range
[3, 6, 9]

1

u/TouchingTheVodka Who's hiring? Jr-Mid Remote/UK - PM me! Oct 09 '20

range is not a function, range is a class. The output is correct.

2

u/scrdest Oct 09 '20

That's a distinction without a difference in Python - all functions are subclasses, either of the 'function' class, or any other class which also happens to define __call__().

3

u/TouchingTheVodka Who's hiring? Jr-Mid Remote/UK - PM me! Oct 09 '20

No, there is a very real difference - when you call range the thing you're getting back is an object of type range. range objects have several useful properties such as a __contains__ method backed by arithmetic rather than iteration, allowing for constant-time membership checking.

>>> r = range(1, 2, 3)
>>> type(r)
<class 'range'>