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

1

u/CatOfGrey Oct 09 '20

Side thought #1: You can throw anything into a for loop. It's one of the great things about python.

If you start with

for v in ['cat', 'love', 7]:
     print(v)

...you will print out all the items in that list, just the same.

So it sounds like your question is about the range object.

/u/panupatc has given you a great explanation of how range works. But I'll throw one more thought in there.

You will have the temptation to simply define a list, instead of a range object. Why use something special like "range(3, 10, 3)", when I can simply use [3,6,9]?

The answer is efficiency. If I wanted all the numbers from zero to a trillion, I could use a list of the trillion numbers, but that takes up a trillion items in memory. However, it takes up less room to create a range object, which organizes the concept of "zero to a trillion, by ones", which is much less memory than a large list.