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/gibbonofdoom Oct 09 '20

The way range works, is it creates a list of values

print range(10)
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

So the for loop works as an iterator, over those numbers: "for each value in this list, do the following"

You can iterate over any list of items in the same manner

for x in ['my', 'test', 'list']:
    print x
>> my
>> test
>> list

As others have said, you can give different arguments to the range function, such as inverting it, or every other value, etc.

1

u/sunnyparm Oct 09 '20

Only a list type makes python iterable??