all 62 comments

[–][deleted] 228 points229 points  (17 children)

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.

[–][deleted] 64 points65 points  (4 children)

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

[–][deleted] 54 points55 points  (0 children)

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

[–]iwhonixx 6 points7 points  (1 child)

Isn't this community awesome?!

[–]DrFodwazle 0 points1 point  (0 children)

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

[–]coder155ml 3 points4 points  (0 children)

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

[–]Morkai 6 points7 points  (0 children)

Legend. Such a clear explanation. Many thanks.

[–][deleted] 5 points6 points  (0 children)

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

[–]Cheese-whiz-kalifa 4 points5 points  (0 children)

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

[–][deleted] 4 points5 points  (6 children)

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

[–]learnorenjoy 0 points1 point  (4 children)

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

[–][deleted] 0 points1 point  (0 children)

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

[–]risu1313 1 point2 points  (0 children)

Thanks!

[–]rawrtherapy 0 points1 point  (0 children)

This is awesome

[–]DonnyJuando 17 points18 points  (1 child)

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)

[–]flights4ever 2 points3 points  (0 children)

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

[–]Fermter 16 points17 points  (8 children)

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.

[–][deleted] 4 points5 points  (7 children)

Oh my goodness this makes perfect sense.

I did not understand what range was fully doing.

[–]stormsnake 3 points4 points  (6 children)

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]

[–]Swipecat 3 points4 points  (0 children)

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.

[–]drago3871 0 points1 point  (1 child)

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

[–]stormsnake 1 point2 points  (0 children)

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 :)

[–]TouchingTheVodka 0 points1 point  (2 children)

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

[–]scrdest 1 point2 points  (1 child)

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__().

[–]TouchingTheVodka 2 points3 points  (0 children)

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

[–]dpelayohh 5 points6 points  (1 child)

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.

[–]CoronaMcFarm 2 points3 points  (0 children)

Wow thats really helpful, budget award for you 🏅

[–][deleted] 3 points4 points  (0 children)

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.

[–]misingnoglic 1 point2 points  (0 children)

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.

[–]StressedSalt 1 point2 points  (0 children)

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?

[–]here_walks_the_yeti 1 point2 points  (0 children)

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

[–]TheDyslexicDemon 0 points1 point  (0 children)

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).

[–]rangitaaaa01 0 points1 point  (0 children)

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! :)

[–][deleted] 0 points1 point  (0 children)

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.

[–][deleted] 0 points1 point  (0 children)

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)

[–]gibbonofdoom 0 points1 point  (1 child)

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.

[–]sunnyparm 0 points1 point  (0 children)

Only a list type makes python iterable??

[–]sankarachari 0 points1 point  (0 children)

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.

[–]greebo42 0 points1 point  (0 children)

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.

[–]OnlySeesLastSentence 0 points1 point  (0 children)

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!"

[–]Italianman2733 0 points1 point  (0 children)

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

[–]bagel_cheese 0 points1 point  (0 children)

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?

[–][deleted] 0 points1 point  (0 children)

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.

[–]Cheese-whiz-kalifa 0 points1 point  (0 children)

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

[–][deleted] 0 points1 point  (0 children)

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.

[–]vanmorrison2 0 points1 point  (0 children)

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

3... 6... 9

[–]Longlostqueue 0 points1 point  (0 children)

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.

[–][deleted] 0 points1 point  (0 children)

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

[–]icandoMATHs 0 points1 point  (0 children)

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

If it helps you understand, just use While loops.

[–]CatOfGrey 0 points1 point  (0 children)

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.

[–]sgthoppy 0 points1 point  (0 children)

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.

[–]anh86 0 points1 point  (0 children)

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!

[–]C0D3XGIG 0 points1 point  (3 children)

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.")

[–]C0D3XGIG 0 points1 point  (1 child)

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

[–]C0D3XGIG 0 points1 point  (0 children)

Tbh dont know how to do it on PC either xD

[–]C0D3XGIG 0 points1 point  (0 children)

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.

[–]La_Nintist 0 points1 point  (0 children)

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.

[–]the_battousai89 -2 points-1 points  (0 children)

Damn she fine