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

228

u/[deleted] Oct 09 '20

range() generates numbers.

If you only pass 1 argument range(5) it will start from 0 and keep going up, and stop before hitting 5. I know sounds strange but that's how it works. So range(5) gives you 0 1 2 3 4

If you pass 2 arguments, range(1,5), same as above except this time it starts from your first argument, 1. So you get 1 2 3 4

The 3rd argument is how each steps increases. By default it's 1. Let's pass a 2 and see what happens?

range(1, 10, 2) --> 1 3 5 7 9. Starts from 1, goes up 2 each time, stops before 10.

63

u/[deleted] Oct 09 '20

Great explaination! I didn't know I could use one or two arguments thanks for taking the time to write this.

55

u/[deleted] Oct 09 '20

Np. You can also go backwards range(10, 1, -1)

6

u/iwhonixx Oct 09 '20

Isn't this community awesome?!

1

u/DrFodwazle Oct 09 '20

It probably has the greatest range of any sub. Some people are incredibly helpful and explain stuff better than anyone else could. But I've also come across some assholes who call you an idiot for not understanding something

3

u/coder155ml Oct 09 '20

In a for loop you can use 1 2 or 3 arguments as shown above

7

u/Morkai Oct 09 '20

Legend. Such a clear explanation. Many thanks.

6

u/[deleted] Oct 09 '20

Range generates numbers, unless you pass an object, range behaves in some ways that not so intuitive.

5

u/Cheese-whiz-kalifa Oct 09 '20

Yeah just try to remember range(start point,end point(not include in output), increment range by)

5

u/[deleted] Oct 09 '20

The stopping before 5 is actually very logical. It stops after 5 numbers have been counted, and as we start from 0, it ends at 4

1

u/learnorenjoy Tabs Oct 09 '20

But what of the example above range(1,5) it still has the argument 5 but doesn't include it when printed out. So in such a case, it may not be so intuitive or 'logical'.

1

u/[deleted] Oct 09 '20

Hmm, that is right. thank you u/gatherinfer for explaining this better

3

u/[deleted] Oct 09 '20

[removed] — view removed comment

2

u/El_Dumfuco Dunning-Kruger sufferer Oct 09 '20

With this design philosophy, it also has a concatenative property: range(a,b) + range(b,c) = range(a,c)

1

u/rawrtherapy Oct 09 '20

This is awesome

16

u/Fermter Almost OK Oct 09 '20

OK, this is more a function of what "range" is doing that what the "for" loop is doing.

Here, the for"loop is just setting v to be every value returned by range(3, 10, 3), and then printing that value.

Range, on the other hand, is doing something special. The 3 values you're passing to range are, respectively, the start, stop, and step. Range starts at the start, stops before the stop, and increments by the step every time.

In this case, the start is 3, the stop is 10, and the step is 3. Therefore, the range returns 3, 6, and 9, in that order (because it starts at 3, 3+3 = 6, 6+3 = 9, and 9+3 = 12, which is bigger than 10, so it stops and doesn't do anything with that value).

From the perspective of the for loop, v is set to 3 first, then printed in print(v). Then, it is set to 6 and printed, and then set to 9 and printed.

4

u/[deleted] Oct 09 '20

Oh my goodness this makes perfect sense.

I did not understand what range was fully doing.

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]

4

u/Swipecat Oct 09 '20

Yeah, it totally does have to be shown in that "annoying" representation, though, because the whole point of "range" in Python 3 is that it does not expand into a list the way it did in Python 2. Instead, it "generates" the values on-the-fly as and when they are requested by the "for" mechanism. It doesn't waste memory space that way.

Putting "list" up-front does read "range" into a fully expanded list until "range" is exhausted.

1

u/drago3871 Oct 09 '20

Why it is an annoying representation for you? If there is large sequence, what would you want to see as an output?)

2

u/stormsnake Oct 11 '20

I think it's not clear to beginners. Something like "<iterable range from 3 to 10 by 3>" might be better (I ran range and got some iterable object).

I see the point of having the repr be valid python where possible, which is why a repr of "range(3,10,3)" is only annoying here, and not broken :)

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'>

18

u/DonnyJuando Oct 09 '20

stop me if I say something stupid. your range(3, 10, 3) parameter tells the program where to start, where to stop, and how to step through the range. your range starts at 3 & stops at 10 & steps on every 3rd integer in between. so your output is the low range start, 3; and every 3rd integer up to your upper limit (10), 6 & 9.

range(start, stop, step)

3

u/flights4ever Oct 09 '20 edited Mar 08 '26

The original post content no longer exists here. The author used Redact to remove it, for reasons that may include privacy, opsec, or security.

handle work gaze fear books profit sugar piquant boast abundant

7

u/dpelayohh Oct 09 '20

Check out http://www.pythontutor.com/visualize.html#mode=edit. It's super helpful for visualizing python execution. Will help make what's happening more concrete.

3

u/CoronaMcFarm Oct 09 '20

Wow thats really helpful, budget award for you 🏅

4

u/[deleted] Oct 09 '20

Did you read the docs too? https://docs.python.org/3/tutorial/controlflow.html#the-range-function

You must get used to reading official docs and repo docs as it will be your go to place for working something out. There are nearly always examples too. It might seem daunting at first but it’s a practice that all developers need skills in.

2

u/misingnoglic misingnoglic Oct 09 '20

A lot of people gave good answers, but if you want to see what the range is, just do:

print(list(range(3, 10, 3)))

This will let you see the range in list format.

2

u/StressedSalt Oct 09 '20

oh hey guys! I know what the for loop is for but i thought the ranges always formatted with colons? Or is that only for strings, e.g. list [ 1:6: -1], but for ranges its zeperated with comma?

2

u/here_walks_the_yeti Oct 09 '20

New student to python, and this sub. I notice that y’all are quite helpful and not as condescending as some other forum sites. Thanks to all who help answer these questions we have

1

u/TheDyslexicDemon Oct 09 '20

Uh I’m also new to programming but here’s what I got: When you’re printing v you’re printing the range specified (range(3, 10, 3)); the first number being where the program will start, the last number being by how much (like counting by 2s: 2 4 6 8), and the middle number(10) is the most the program can go up to. Remember that the middle number is non inclusive (so the most is actually the middle number - 1).

1

u/rangitaaaa01 Oct 09 '20

The syntax for the range function is range(start, stop, step). And the range function returns a list of numbers for the FOR loop to iterate on.

One point to note here is that ‘start’ing value is included but ‘stop’ value is not. And step is the incremental value which will be added to ‘start’

So, going by your example range(3,10,3):

We begin iteration at start so v= 3(which is also less than the stop value) Then the second time we increment by 3, so v=6(also less than stop value) Then the third time, we increment by 3, so v=9(also less than the stop value) When it is increments to 12, its greater than 10 and hence rejected

So the range function returns [3,6,9]

Now in the for loop,

Rewriting it as pseudocode:

For v in [3,6,9]: Print(v)

So first iteration v=3, output: 3 second iteration v=6, output: 3 6 third iteration v=9, output: 3 6 9

Hope this helps! :)

1

u/[deleted] Oct 09 '20

The many ways to configure a for loop in Python is the one thing that I find the most perplexing as someone who's primary language experience is in the C/C++ multiverse.

1

u/[deleted] Oct 09 '20

Basically v is an integer that takes on the values described by range(3, 10, 3). Here the range() function is giving v and initial value of 3, and then increasing it by +3 at the end of each iteration until the value has reached 10 (or the closest value to 10 before exceeding it)

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??

1

u/sankarachari Oct 09 '20

Hi,

The v' is variable in which range 3 to 10 having offset of 3, finally prints variable v'.

We have 3,4,5,6,7,8,9,10 in range of 3 to 10. which is first two parameters in range(). The third parameter is for every third item to its predecessor.

1

u/greebo42 Oct 09 '20

I had written programs in C several years ago, went a long time without programming, and then started to pick up Python, and the for loop puzzled me at first.

Now I understand that what it's doing is iterating over some set of things which are arranged in a defined order. That set of things could be a list of strings. That set of things could be a list of integers. Or whatever (I'm not talking about the python "set").

So, the range function generates a set of things in a defined order. The example shown is pretty much like the way C does it. The neat thing is that for can be used in many other ways, so you are not /limited/ to the way C does it.

1

u/OnlySeesLastSentence Oct 09 '20

It translates to "let's make a changing variable called v. I want to start it at 3. So v is three. (That's what the first 3 is). Now, I want to keep doing it until we reach the second number or are forced to go higher than it, which is 10. But before I do that, let me increase it by the third number. 3+3=6. That's less than 10. So show 6. Now increase by 3, that's 9. Show it. Increase by 3... Oh no, it's more than 10. Abort without printing!"

1

u/Italianman2733 Oct 09 '20

I don't know if it's been said already because I didn't read every comment. But...for loops can be used with other things besides ranges. One example is lists. If you type something like:

greeting_list = ["hello", "hi", "how are you"]

for i in greeting_list:print(i):

RESULT:

hello

hi

how are you

1

u/bagel_cheese Oct 09 '20

Is the range() method inclusive for offset? Speaking from a java perspective..anytime we usswith loops,or substrings..the language uses zero based indexing..I'm learning a little of python, is it set up the same way?

1

u/[deleted] Oct 09 '20

list_of_letters + ['a', 'b', 'c']
for letter in list_of_letters:
print(letter)

Try this code out and see what happens. Make sure to indent the print statement. For letter in.. means that you're defining each letter in the list as "letter". So first it will define letter = a. Then whatever code you have written will be executed for a. So it will print a. Then it will move on to the next item in the list and define letter = b, etc.

1

u/Cheese-whiz-kalifa Oct 09 '20

If you’re having trouble python crash course is a great book. I had trouble understanding a lot until I read that book.

1

u/[deleted] Oct 09 '20

When you say range(3,10) it’ll list numbers 3 through 9. They last ‘3’ in the range statement means it’ll select every third number, so 3, 6, 9.

1

u/vanmorrison2 Oct 09 '20

it starts at 3, ends at 10 with a step of 3...

3... 6... 9

1

u/Longlostqueue Oct 09 '20

3 is your starting number 10 is your final number The last 3 determined that you are using multiples of 3

Another thing, if it is 3,10. That mean it would include every number except for 10.

1

u/[deleted] Oct 09 '20

For each value in the range between 1 and 10, print out every third number.

1

u/icandoMATHs Oct 09 '20

OP, I avoided For loops for 12 years. It's syntax sugar.

If it helps you understand, just use While loops.

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.

1

u/sgthoppy sgtlaggy Oct 09 '20

Don't see a reply where someone has described the stop parameter quite to my liking. The way I came to understand it is this is where the range stops, not where it ends.

When you iterate and it reaches the stop value, it stops. It doesn't see it, return it, then end, it stops upon seeing it or a value past it in the range. It's not the end, or last value of the final sequence.

1

u/anh86 Oct 09 '20

You're 'iterating' through some group of values, assigning each value in the group to v, running the code block, then assigning the next value to v, running the code block, until each value in that group/range is used.

In your example, the group of values is defined by the range() function and you've passed in three parameters -- range(start_value, stop_value, increment). In other words, your group is the values between 3 and up to (but not including) 10 with step increments of 3. Thus, your group of values is 3, 6, and 9.

So, on the first iteration of the loop, the value 3 is assigned to your variable v and the code block is run. In this case the code block is to simply print whatever is loaded into v. After printing 3, 6 is assigned to v and the code block is run again.

You also don't have to use the range() function to set your group. You could define your own list like for v in ['I', 'love', 'Python']: and you'd get each of those values printed. You could load some list into a variable like my_list = ['I', 'love', 'Python'] and then call for v in my_list:.

Hopefully that clears it up!

1

u/C0D3XGIG Oct 10 '20

My favorite for loop.

import time import sys

def type(str): for char in str: time.sleep(.1) sys.stdout.write(char) sys.stdout.flush()

type("This is just like printing. \n") type("Except you must use escape n.")

1

u/C0D3XGIG Oct 10 '20

Sorry I'm on mobile cant figure out how to make a code block.

1

u/C0D3XGIG Oct 10 '20

Tbh dont know how to do it on PC either xD

1

u/C0D3XGIG Oct 10 '20

P.s. This is really BAD. You probably shouldn't define it as "type". Because type is predefined in python.

Best way around it is to just rename it qtype or quicktype.

1

u/La_Nintist Oct 15 '20

Idk if this got answered yet but life was good until loops screwed me over. I’m very new to programming as well. The way I think about this is Print a range of numbers from 3-10. The third variable is telling the program to skip every 3 numbers. So it will print 3,6,9.

-1

u/the_battousai89 lifelong beginner Oct 09 '20

Damn she fine

0

u/[deleted] Oct 09 '20

[deleted]

21

u/[deleted] Oct 09 '20

Thank you for slowing it down for me. Really appreciate it.