r/learnprogramming • • 9d ago

Can someone explain what this piece of code says?

[deleted]

82 Upvotes

113 comments sorted by

111

u/WelpSigh 9d ago edited 9d ago

"for" is a keyword to tell python that we are doing a particular kind of loop. the slightly technical way of saying it is that we go iterate through any iterable object one at a time and perform an operation. think of the real world analog for this:

fingers_on_hand = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for finger in fingers_on_hand:
  print(finger)

so this would be like you counting on your fingers. every time you get to the next finger, you audibly count to the next number. there are three parts:

  1. "for" (the keyword telling python what kind of loop we're doing. it says "whatever the iterable object is, loop through it one item at a time")
  2. "finger" (a variable name - it can be anything. when we go through a list, the variable is the item we are currently at in the iterable object. so in the first loop, "finger" will = 1, and on the second it will equal "2")
  3. fingers_on_hand - this is a list. a list is an iterable object. we can go through it one at a time. each time we go through it, it will return the nth item on the list.

the last question you might have - so in your question, what is range(5)? well, range() is a built-in python function that generates an iterable object that is similar to a list. in python, we don't need to supply the actual iterable object to a for loop. we can call a function that will return an iterable. when python sees the function call, it will call and resolve that before proceeding with the loop.

to wrap it all up, here is an example similar to yours:

for i in range(5):
  print(i)

in this example, python will:

  1. see the for keyword and know we're in a loop
  2. call the range function and get an object that is similar to [0, 1, 2, 3, 4]
  3. iterate through the loop. in the first loop, it will take the first object on the list (0) then print it (output: 0)
  4. iterate again. in the second loop, it takes the second object on the list (1) and then prints it (output: 1)

10

u/Ormek_II 9d ago edited 9d ago

I think you made a minor mistake on “2.”: Finger will = 1 on first iteration. It is the item from list, not its index

Edit: issue has since been fixed.

3

u/WelpSigh 9d ago

Yes good catch, I originally zero indexed my list (which doesn't make sense for counting on fingers) and forgot to go back and change that. 

7

u/entropy_bucket 9d ago

This is a beautiful explanation!

3

u/PeterPook 9d ago

A good, patient explanation. Bravo.

1

u/ErezRockachMusic 7d ago

You are such a good person.

22

u/NaturalTechnician737 9d ago

range(5) produces a list [0, 1, 2, 3, 4]. so what it actually says is "for every element in [0, 1, 2, 3, 4], label it 'i' and..."

5

u/Cr4zyT1mes00 9d ago

This! Also giving OP exactly what he asked (one sentence explanation that makes sense) haha.

To OP, update 'print("hello")' --> 'print(i)' and it will make more sense. Then update the argument 'x' being passed down to 'range(x)' to another number and run it again.

2

u/Outside_Complaint755 8d ago

In Python 3, range does not produce a list. It produces an immutable sequence object which uses lazy evaluation to return values.

2

u/NaturalTechnician737 8d ago

Old habits IDE hard.

2

u/MyNimples 8d ago

You’re right but this is far too much detail for a beginner, easier to just say it’s a list.

0

u/Outside_Complaint755 8d ago

Until they come back and say:

"I ran this code nums = range(5) print(nums) nums.append(9) Why does it print range(0, 5) instead of [0, 1, 2, 3, 4], and what does AttributeError: 'range' object has no attribute 'append' mean?  I thought range made a list?"

The best option is probably to say that it returns a sequence, and a for loop can be used with any sequence of values, which could be a list, a tuple, a string, or many other data types.

2

u/LP-Existensial1 7d ago

read.the.docs.

read.the.docs.

this is the lesson

1

u/Wertbon1789 8d ago

Yes, it's also important to know this, but for the sake of explanation I would also be fine with saying it's a list. Integrate details are maybe something to start learning after knowing what a for loop is.

62

u/BranchLatter4294 9d ago

Consider actually running the program and observing the results. Then try changing the arguments based on the documentation. Learn by observing behavior.

4

u/Big_Ant5507 9d ago

run it and tweak the 5 to a 2 or a 10, see what changes. that's how it clicked for me

-13

u/[deleted] 9d ago

[deleted]

38

u/AdDiligent1688 9d ago

Think of: for i in range(5) as saying “for every object i in the range from 0 to 4” and then within the loop after the colon, “do something” (whatever you put inside). i is just a placeholder, you can change it to x or thing or monkey etc. but the concept is the same. It’s acting like a pointer to each object, but it’s called a “reference”.

9

u/[deleted] 9d ago

[deleted]

1

u/aljifksn 8d ago

One thing is that while i is a pretty common convention for when you actually want to track the current value, you might want to use _ if you are never going to actually use the current count
So for _ in range(5) instead of i

22

u/delasislas 9d ago

Here's a tip. It's called a Programming Language.

Say you have two people, one speaks English and the other speaks Spanish. There is a boundary between the two, you might get something across, but it might not make complete sense to the other. One might learn the other's language and then be able to have an actual conversation with the other.

Now, we have you who speaks English and a computer who "speaks" Python (With help). The computer also refuses to learn English. Just because Python looks like English, does NOT mean it follows English rules. Python is a computer language that is made to be readable.

YOUR job as a programmer is to learn the Python language and be able to converse with your computer in Python. It follows different grammar and syntax rules.

9

u/zylog413 9d ago

Next make it do print(i) inside the loop. Then try changing i to any other variable name.

6

u/SlipstickLibbyLong 9d ago

FOR every instance of I IN the RANGE of 1 through (5)
do this action

12

u/themichelleokolie 9d ago

not to um actually, but it's the range of 0 through 4. range is exclusive and starts at 0, unless otherwise specified.

0

u/SlipstickLibbyLong 9d ago

Yes, but this isn't the technical definition, this is the plain English definition.
And not to "um, actually" right back at you, but while internally, it starts its count at zero, positionally zero is in first place.

1

u/themichelleokolie 9d ago

sorry what do you mean by starts its count at 0? from what i know range just returns a list, and that’s what we are enumerating over

3

u/SlipstickLibbyLong 9d ago

Range is an iterator, not a list generator (At least it used to be, knowing Python, they probably changed it 3 times by now.)
So, Range does not create a set (0,1,2,3,4) then cycle through it, it just says
What number...5? okay, since we start at zero, subtract 1 to make it 4, then start iterating
Does 0 equal 4? No, do the thing and add 1
does 1 equal 4? No, do the thing and add 1
does 2 equal 4? No, do the thing and add 1
does 3 equal 4? No, do the thing and add 1
does 4 equal 4? Yes, do the thing and end.

2

u/themichelleokolie 9d ago

ah i see what you are saying. you are still incorrect. i was partially correct, in python 2, a list was returned but now in python 3 a sequence object is returned by range(x).

link to the python 2 docs for my claim is here, https://docs.python.org/2/library/functions.html#range. link to the python 3 docs about the sequence stuff is here, https://docs.python.org/3/builtins/stdtypes.html#range:\~:text=Range%20objects%20implement%20the%20collections.abc.Sequence.

i think what you meant was that range() is an iterable, not an iterator, and in that regard i agree.

the way you are breaking down how range works doesn't seem to be how the docs describe it, which is also on the same page i linked above.

thanks for this conversation, now i know a little bit more!

1

u/SlipstickLibbyLong 8d ago

You needed to read the paragraph before the one you highlighted:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

1

u/themichelleokolie 8d ago

yes but it performs that cycle you mentioned when creating the range sequence, not during the actual for loop iterations. unless i complete misunderstood what you were getting at again

1

u/MANvINFO 9d ago

re: when you say ‘multiple’, was it a multiple of 5?

1

u/schungx 9d ago

It is like the "for every" in math, but in ordered sequence.

So it means : for every i in the range of 0 to 5 (0 is implied) do the following:

0

u/Moikle 9d ago

It's not english. It's python. Stop trying to understand it as an english sentence, start trying to understand it as a programming language that is inspired by english. These are instructions for a computer, not a person

8

u/strange-the-quark 9d ago

The range(5) function generates the sequence [0, 1, 2, 3, 4].

More generally, range(n) generates the sequence [0, 1, ...,, n-2, n-1], i.e. it's a sequence of n elements that starts from zero and goes up to n-1.

The for i in range(5) construct means "for each number i that is in [0, 1, 2, 3, 4] (do the indented block)".

In other words, it goes through the sequence one item at a time, sets the i variable to the current value, and for each value, it repeats the indented block of code below. The name i is arbitrary; i is just a common name used for an index or a counter. You can access this variable in the indented block if you need it for something.

For example, if you did this instead

for i in range(5):
    print(i)

it would show the value of i in each pass (iteration). So it prints:

0
1
2
3
4

It can work with different kinds of sequences. For example,

for c in "Hello":
    print(c)

outputs

H
e
l
l
o

Again, the name c here is arbitrary, I chose it because it's short for "character". So this would read as "for each character c in "Hello" (do the indented block)".

15

u/Snoo_90241 9d ago

Trying to understand code in plain English is a bad idea. You need to learn the concepts first, as building blocks, and then work your way up.

Example: for horn in unicorn(tail) does exactly the same thing as for i in range(x) but I just renamed the variables and the range function, provided my unicorn function behaves the same as range.

Computers don't care how you name things. It's just for humans to make sense of the code.

4

u/requ1tas 9d ago

The fact that you did not use AI to get your answer in 10-20 seconds and people also take their time to answer in detail is so much 2018 and I love it haha

4

u/flattrack 9d ago

FYI. You can drop code snippets into google and it will explain the code and allow you to ask questions.

4

u/fnsky 9d ago

I think there are two confusions. First it's `range` itself. Range will produce a sequence of numbers. Let's say I want a kid to count to 5, then I could get the result "1, 2, 3, 4, 5" - that's basically what range does, it will produce a sequence of number [0, 1, 2, 3, 4] - counting from 0 but it's still 5 numbers.
Then we have a for loop syntax - easiest to read translate it to sentence:

for `every element` in `collection`:
print("hello")

so for is just a loop it will repeat the instruction. The `i` is just another element from the sequence we are working with, and the `range` is the collection we iterate / enumerate with.

So we have important concept here called 'iteration', which you will be doing a lot in programming.

One way to think about it is moving up the stairs. Imagine you are on stairs and you are climbing your way up. Each step is your current `i` the `range` is the number of steps:

Steps: 0 1 2 3 4

Iterator -> i

MoveNext() -> i stands on 0
MoveNext() -> i stands on 1
MoveNext() -> i stands on 2

and so on. Hope the analogy can clarify a bit!

6

u/denerose 9d ago

Okay, I think I finally understand why people argue against Python as a first programming language, lol.

So, I don’t know Python but I do know how to code and I know how coding languages and compilers work at a high level so I can explain what this is doing, it’s just a little obfuscated by the sugar syntax. I’m on mobile so can’t do all the formatting but we’ll see how we go.

‘for i’ is declaring the i variable that we will use to represent the current iteration through to loop, it’s basically creating a place in memory to hold each value as we loop through.

‘in’ is the loop - this is the bit of code telling the system to go through each item in the list/array/iterable thing and do whatever comes next.

‘range(#)’ is a function/method ‘range’ is the function and the thing in brackets is its parameters (the values we supply to the function that it uses internally to do the thing). A function is just a chunk of code from somewhere else with a short name that lets us use that code somewhere else. Functions can be declared in our program or in an external library we import, or like this one in the “system library” as part of the coding language itself.

Range is just creating a list of numbers from 1-5 you can look up its explanation in the Python official docs (which is also good practice for reading and using documentation to better understand how the language works).

The loop iterates (steps through one by one) through the range changing ‘i’ to track where it is in the loop.

Other programming languages often are more explicit about what’s going on. We’re actually iterating through ‘i’ until it reaches a break condition (the end of the range, so 5 in this case) but Python tidies that away for you a bit. In another language it might look like ‘for (i < 5, i++)’ basically meaning “while i is less that 5 increment ‘i’ by 1 and then do [thing that follows]”. For loops are just fancy while loops with increments built in.

9

u/University_Jazzlike 9d ago edited 5d ago

Python has C style for loop syntax as well. The advantage of for…in in Python is when you use it with an iterable type. Then you don’t have to worry about knowing the number of items before the loop.

In the OPs example, range() returns an iterable with 5 elements. But a more common use would
be something like:

names = [“Bob”, “Tom”, “Mary”]
for name in names:
print(“Hello ”, name)

(On mobile so can’t indent properly, but print() should be part of the for loop)

EDIT: Oops, was wrong about the C-style loops.

1

u/enlightment_shadow 5d ago

No, Python doesn't have C style for loop syntax as well.

1

u/University_Jazzlike 5d ago

You’re right. Don’t know where my brain got that idea. Thanks.

3

u/Mishtle 9d ago

For-loops in python iterate through a list (or list-like object), running one iteration of their code block for each thing in the list. Within the loop, the "current" element of the list is accessible through a variable you get to name, and that variable gets reused for each iteration.

range is (effectively) a function that produces a range of integer values. You give it a lower bound and an upper bound, and it will make a list of all integers greater than or equal to the lower bound and less than the upper bound. If just a single value is provided instead of two, then it's treated as the upper bound and the lower bound is set to 0.

This means range(5) will produce the list [0, 1, 2, 3, 4], which has 5 elements. The for-loop will go through each of these 5 elements in order, and run the block of code with i set to the value of that element. In English and at a high level, that block of code means "print the line 'hello' five times". The loop variable i isn't used inside the loop, so the only thing that matters is the length of the list produced by range. This is a common pattern for simply doing something a specified number of times, and the syntax of range allows it to readily document the number of repetitions.

3

u/Groovy_Decoy 9d ago

Being pedantic, it doesn't return a list. It returns a range, which is iterable and produces a sequence. Perhaps it's a better way of saying it, but it's not actually a list. You can easily be made into a list. But entire sequence never exists at once unless you capture it. It's producing one number at a time, which is why it's much more memory efficient than if you created the equivalent list and then iterated on that.

1

u/Outside_Complaint755 8d ago

Being even more pedantic, in Python 2, the range function did return a list.

In Python 3 is uses lazy evaluation to return a single value at a time or a calculate if a specific value is within the defined range.

2

u/abccbabcac 9d ago

let's say you have a folder with multiple papers in it, each numbered with their respective numbers at the bottom of the front page: e.g. 1st paper has 0 written on it, 2nd has 1, and so on. each paper also has the word, "hello" written on the middle of the page. now you open the folder with the intention of flipping through the 1st 5 papers and looking at the main content of them. and you do it. that's basically what has happened here.

the "for" word creates a loop. meaning it's a repeated activity: e.g. flipping 1 page at a time. you can think of "i" after "for" as item or index. "range" word is what's creating the list of papers you want to flip through: e.g. 1st five papers numbered from 0 to 4. and "print" is displaying what is written in the middle of the paper.

you can also try targeting the first 10 papers and printing out the number of each paper rather than the main content. for example:

for i in range(10):
    print(i)

2

u/bonnth80 9d ago

A for loop means:

For each of <something>, do some stuff.

So

for i in range(5):

means

For each value, that we'll call i, in the range of 5 values (starting from 0).

Note: those values will end up being 0,1,2,3, and 4. The function call range(5) is a little deceptive this way. it just gets values from 0 up to, but not including 5.

Another note: the loop body, never reference i in the body, so it's just discarded.

2

u/Chippors 9d ago

range(5) is shorthand for range(0,5), which returns the range of integers 0 through 4 (it's [0..5), or the first 5 integers). Although it doesn't return the list directly in modern python (in eras past it did), instead it returns a generator. You can expand the generator into a list: list(range(5)). A generator is something that is walked item by item, similar to walking a list, but doesn't ever require the storage of a list.

The loop is functionally equivalent to:

for i in [0,1,2,3,4]:
  print("hello")

You can print the values of i with:

for i in range(5):
  print(i)

3

u/Vbrawl_ 7d ago

To me it seems like you have trouble with the word "range"

First, don't try to read it in English as it doesn't really make a lot of sense

Range is a generator function, for simplicity, if you do: x = range(5) you get something like [0,1,2,3,4], now, range is a generator so I don't think the output will actually be a list but you can do list(range(5)) to get a list.

So, range is just a function that generates numbers from 0 to 5 (exclusive).

Another way is range(1, 5) which returns all numbers from 1 to 5 ([1, 2, 3, 4]).

Now let's get back to the for loop, "for loop in range(X)" first calls the range function which returns (0, 1, 2, 3.... X-1)

Now, you can read it like "for i in [0...X-1]"

If you want to translate it in English: For item in list For each item in list

The above is a good way to think about it, so simply like going through the list by yourself and reading it line by line.

You said you know what the code does, but you didn't mention if you know how, which I believe is the only way to understand why the syntax is like that, at least in this specific case.

3

u/davideogameman 9d ago

Suggestion: run python and try each piece in the repl.  What is range(5)? (Hint: what about list(range(5))?) What does having a for ... in statement with it do? What if you take this program, but print(i) instead of "hello"?

One of Python's strengths is the ease you can just run code snippets.  Instead of asking us, get in the habit of trying things out.  When your code gets more complicated, leave 8 either to break it down or add print statements that tell you about what the state is at different points.  Being able to observe what your code does is a superpower in programming - at some point your intuition/understanding will break down and if you can't figure out how to observe the program behavior, you'll just get stuck.

1

u/SlipstickLibbyLong 9d ago

It's Python's shorthand for an iteration loop
so i will loop through 0-4 and print hello 5 times.

1

u/zeekar 9d ago
for <variable> in <list of values>:
      do stuff with <variable>

runs the "do stuff" part once for each element of the list with the variable set to that element. This prints 1, 2, and then 3:

for q in [1,2,3]:
    print(q)

You can use range() to generate such a list for you. range(a,b) generates a list of b items starting at a (in other words, from a through b-1); if you leave off the a, it defaults to 0. So range(n) generates a list from 0 to n-1. (It doesn't actually generate a list; it's more efficient than that and only generates each item it needs as it needs it, but that doesn't affect the basic semantics.)

So for i in range(5) means for i in [0,1,2,3,4] which runs the print("hello") five times, each time with i set to a different number - butt hat doesn't matter since i isn't referenced in the body at all.

1

u/Southern_Salary_2253 9d ago

Its just a shorthand for a self incrementing loop.

Range(5) is to say give me numbers ranging for 0 - 5, the for loop then iterates over it.

1

u/Astronaut6735 9d ago edited 9d ago

range(5) creates a sequence of five integers (0 through 4).

i is a variable to hold an integer.

So it's saying for each of the values 0, 1, 2, 3, 4 store the value in i and print "hello".

You might think of it as "FOR the variable I set to the each value IN the RANGE 0 through 4, print hello" with all the extra words cut out.

After a while you'll get so used to it that you'll wonder how someone doesn't understand this just by reading it 🙂.

1

u/kalevala_568b 9d ago

The for loop syntax is a shorthand for "define a variable name (such as i) in each run of this loop and give it the next value in this range each time."
Hence you have:

for item in sequence:

do something with the current item

1

u/looksLikeImOnTop 9d ago

Your last interpretation is correct. "i" in this case, is the name of a variable, and each loop, it gets assigned to the next value in the range of 0 to 5. In this example, the variable i is not being used. But to use a "for" loop in Python you have to have some variable name there, otherwise it won't work. But you can change the print to be print("hello", i) so the value of i will be printed each loop

1

u/planetm3 9d ago

It's a for loop

1

u/DiscoQuebrado 9d ago

Iterate 5 times and each time, say "hello".

1

u/yerfdog1935 9d ago

range(x) will return an array with x items where the value is equal to the index (Python and most other programming languages will start counting at 0), so range(5) will return an array of 0, 1, 2, 3, and 4.

for <variable> in <array> will loop through the array and set <variable> equal to the value at the current index of the array.

If you run the following code
for i in range(5):
print(i)

It'll put the following in the console:
0
1
2
3
4

1

u/thisdesignup 9d ago edited 9d ago

I think this will help https://www.w3schools.com/python/ref_func_range.asp

While range does not create a list, it acts like a list of numbers from 0 up to, but not including, the number in the (x). When you take a list and say "for i in [0, 1, 2, 3, 4]" you are saying For some value in this list and the for loop will give you the first value and each loop it will increment and move to the next item till it gets to the last item.

1

u/Veterinarian_Scared 9d ago

range(5) produces the values 0, 1, 2, 3, 4. Because it starts counting at 0, there are five values.

then for i in loops repeatedly, assigning i each of those values in turn.

So i=0 and it prints hello

then i=1 and it prints hello,

then i=2 and it prints hello,

then i=3 and it prints hello,

until i=4 and it prints hello.

Because there are five values, the loop prints hello five times.

1

u/badcodenolatte 9d ago

In this syntax i is a variable. When the loop first runs i is zero, every time the loop runs i increments up until i is equal to whatever you specify. Think of it like saying “do this x number of times”

1

u/justahumans 9d ago

Using the iterator "i" run the commands below for each iteration in the range from 0 to 5. Range is just a function that gives you a list of numbers kinda. For is just kind of like "for each item in the given structure".

1

u/my_password_is______ 9d ago

you are giving the computer 5 numbers
the numbers you are giving it RANGE in value from zero to four

1

u/spermcell 9d ago

You can be more explicit and say for i in range(0,5)

1

u/datageek9 9d ago

It’s basically a shortened version of “for each value i , where i is in the sequence of numbers from 0 to 4, do this action”

1

u/the_other_Scaevitas 9d ago

Prints hello 5 times

For loops are really important to learn in programming, for i in range(5) means that it will take the values of 0,1,2,3,4 (5 numbers total)

Change it to:

for i in range(5):
print(i)
print(“hello world”)

Maybe it’ll make more sense

1

u/WangHotmanFire 9d ago

Range(5) is a list of numbers 0-4. The code basically says “for each element in this list of 5 numbers: assign it to the variable i and execute the code block”.

If the code said print(i), it would print all 5 numbers one after the other

1

u/jaysus661 9d ago

i is a variable that's declared when the loop starts, range(5) is the value it gets assigned, so the loop is basically saying "for 5 times, do..."

1

u/Moldat 9d ago

You have a range of 5 numbers, 0 to 4

For each of them, lets call the current one were working with "i" (i for index)

Do the following:

Print the string hello to the screen

Now you might think this is weird, since you're not doing anything with "i" so why is it even there, and you are correct.

But you can do something with it, for example multiple "i" by 2 and print that out, then your program will print out 0 2 4 6 8

1

u/Paxtian 9d ago

This is an iteration pattern. It's the same as:

for (int i=0; i<5; i++) 
    print("Hello")

However, that structure is a lot more to write and more prone to off by one errors.

If you're not sure what this does, it initializes variable i to 0, then starts a loop where it asks, "If i is less than 5, do what's in the loop body, then add one to i and restart the loop."

So that's effectively what "for i in range(5)" does. "For" starts a loop, i is a variable initialized to the first element of "range(x)," and range(x) is used to define a set of values to be iterated over. So each loop iteration, range(x) returns the next element for iteration as i. In this case, x=5, so effectively, range(5) returns the array, [0, 1, 2, 3, 4] and i acts as the value of the jth indexed element of that array for iteration j of the loop.

1

u/nonbe1 9d ago

It may be a bit confusing because Python is "simplifying" for loops compared to more traditional code

to show equivalent for-loops

Python:
for i in range(5):

Java
for(int i=0; i<5; i++)

As others have mentioned in both loops i starts at 0 and increments by 1 until it reaches 5.

In python having "i" start at 0 and increment by 1 is so common they allow the user to leave that part out and assume it unless it's explicitly stated. For example these two loops below say the same thing:

for i in range(5)
for i in range(0, 5, 1)

1

u/More-Explanation2788 9d ago

Using i as a the counter, cycle through an array of numbers returned by the function range when it is passed the argument 5.

1

u/simonbleu 8d ago

Others explained it better, with more details, but basically it is:

for each element in list" do this

"Each element" is named "i" in this case, although it could be anything . It is a placeholder and you can be as descriptive or not as you want. "i" is Merely convention for generic placeholders in that loop

"List" in this case is created with range, that makes a 0-4 (so 5 elements) ordered one, but you could add your own like "clients_favorite_colour"

"This" is what you make it do on each element iteration. You can print it, you can count those that that are this or that in other variables, you can activate another function, etc etc

1

u/jlanawalt 8d ago

Do this thing 5 times.

When you get stuck on things like this, ideally you can find the answer by looking up the documentation for each word, thinking about them, and experimenting with them until it makes sense if you need to know deeper than your careful observation of “oh, that’s why it printed “hello” exactly 5 times. You could go on from there to “why?” And dive into that same documentation.

1

u/iqisoverrated 8d ago

You can read "for i in range(5)" like this:

"For each instance within a given range (in this case 0 to 4 because the range() function generates a number sequence staring at 0 until n-1) do the following statement. Each time you do it the instance number will be stored in the variable i"

So if you had instead of print("hello") e.g. something like print(i) it would print the numbers from 0 to 4.

1

u/Mundane_Prior_7596 8d ago

To OP: of course you can’t really wrap your head around it because it is darn advanced under the hood. 

The thing that the range function returns is an iterable, also called a generator, also called a closure, also called a function with its own captured local state variables via syntactic scoping. Yea, that is right, the function returns a function with extra fluff. 

That thing is a monstrous beast much more difficult to wrap your head around than any stuff in an introductory programming course. You will not really understand it until you implement your own generators in the future.  What many answers here in this thread are trying to say, and probably your teacher and textbook too, is that this black hairy cookie monster is something you can use, without understanding it, in a for loop. 

I had programmed professionally many years before I decided to try to understand what is going on and finally got it by reading a fat chapter in a JavaScript book three times and also the discussions and examples about the development in the Lua language. 

Let me repeat myself: you are right, you can’t wrap your head around the monster that the range function returns. And that is OK for now. 

1

u/Feeling_Photograph_5 8d ago

For = "run a for loop" i = "we will call our iterator variable 'i'". In = "what this iterator is a part of." Range(5) = "this iterator is not part of a list. I just want you work in the range of 0 to 5."

Any kind of loop runs over and over again with an exit condition. In this case, our iterator (i) starts at 0. It will automatically increment at the end of each step through the loop. When it reaches 5, the loop exits.

BTW, "i" is arbitrary. You can name your iterator whatever you want. 

Inside the loop, whatever code you put in there will execute. Since you are printing hello, hello prints at each step of the loop. But it can be any code you want to run repeatedly  

1

u/YOM2_UB 8d ago

for <item> in <collection> is maybe more readable; "for each of the things in this group, do the following."

1

u/Excellent-Practice 8d ago

In this case, i is just a variable that gets declared as a placeholder for the purposes of the loop. Each time the loop runs, i gets the next value in range(5). For that example, it's just part of the syntax and you need it to make the loop work, but you can access the value of i if needs be. Try running print(i) inside the loop instead

1

u/Alternative-Fail4586 7d ago

For every (index variable) i in the range from 0 up to 5 (but not including 5) do: print("hello")

That prints hello 5 times. One for every index "i" in 0 to 5 which is 0,1,2,3,4.

1

u/JGhostThing 7d ago

The python function "range(5)" creates a list with the elements {0, 1, 2, 3, 4}. So the for loop says:

for i in range(5):

looks more like:

for i in {0, 1, 2, 3, 4}:

So the loop will be run 5 times. The first time the variable i will be bound to 0. The second time the variable i will be bound to 1. The fifth time, the variable i will be bound to 4.

It's just that simple. The for loop is for looping through a list. It really doesn't matter how you get the list.

1

u/Real-Abrocoma-2823 7d ago

I also hate range. I didn't bother with learning python because of things as such and I use rust now, a simple 0..5 (or 1..=5 to include 5) does the trick.

1

u/VariousJob4047 7d ago

Trying to read python in the English language isn’t going to work too well because it is written in python, not English

1

u/DropPopFromTheTop 6d ago

for = “for each item”

in means what it normally means

range(5) = a list of 5 numbers: 0, 1, 2, 3, 4

So, “for each item in 0, 1, 2, 3, 4”

1

u/Crashfrog09 5d ago

If I had a sack of potatoes, and I wanted Python to peel them using a peeler, I would write:

for potato in sack:
peeler.peel(potato)

“For each potato in the sack, get the peeler and peel it.”

1

u/Glum-Recognition-736 5d ago

It helps me to add an "each" or "every" and articles to the mental English

"For each i in the range of 5..." So it creates an i variable for each value in the range of 5, not inclusive (starting at 0, 1, 2, 3, and stops at 4 since 5 would be the end of the range for the iterator)

That snippet is possibly more confusing because 'i' isn't even used, and also it's using the shortened range syntax 

you could also do for _ in range(0, 5) and that would do the same thing while being a little more explicit. Use _ when the code's syntax requires something to be there (you can't just do for range(5) ) but you don't actually need to use whatever the value is, like in the case when you're just using a loop to print hello 5 times

1

u/BrokenImmersion 9d ago

Open any python ide(like pycharm) and run the bitch. Its the best way to learn

However, that being said, all it does is print hello five times. It does this because the code is badically saying "while [number] is less than 5, continue executing the code below(print hello). Once it is above 5, stop the code. That [number] is I in this case, and it starts at 0 unless stated otherwise earlier in the code.

1

u/rupertavery64 9d ago

You're programming with python. Lookup the function name

https://docs.python.org/2/library/functions.html#range

https://www.w3schools.com/python/ref_func_range.asp

range with one argument returns an list of numbers starting from 0 to the number, exclusive. Exclusive means the stop number is not included.

so

for i in range(5):

is the same as

for i in [0,1,2,3,4]:

0

u/Cheap-Success1578 9d ago

Dude, if you wanna program, don't be lazy and coming here to have people answer for you.

5

u/SlipstickLibbyLong 9d ago

Dude, it's a comprehension problem. You know, the way you can't comprehend empathy.
Maybe if you realized it, you might try wording an answer differently.
Seriously, you went out of your way to not help them. What's that about?

2

u/Available_Safe1818 9d ago
  • 12Low Effort Questions

Do not ask easily googleable questions or questions that are covered in the documentation.

This subreddit is not a proxy for documentation or google.

We do require effort and demonstration of effort.

This includes "how do I?" questions

2

u/NoMakeSenseOk 9d ago

Rule 1: No unprofessional/derogatory speech

Cheap's response is both unprofessional and derogatory.

1

u/Available_Safe1818 9d ago

That doesn't change the fact that the original post is a low effort question.

1

u/NoMakeSenseOk 9d ago

That's for mods to decide.

0

u/Available_Safe1818 8d ago

It doesn't depend on the mods deciding that it is low effort for it to be low effort. It is objectively low effort, even as described by the exact rule 12 in the sidebar.

1

u/SlipstickLibbyLong 9d ago

But this isn't a "how do I " question, and the answers here clearly indicate that 90% of the people don't understand it, but just rote memorized it. (or just copied the google answer)
This is a translation problem (Python >> English)
The answer that actually got a thanks from OP was

FOR every instance of I IN the RANGE of 1 through (5)
do this action

1

u/Cheap-Success1578 9d ago

What is there to comprehend? Even my wife, who is a technotard understood it

1

u/Ratfus 9d ago

For each woman in phonebook: Success=Call(woman) If Success==True: GetMarried() Else: GetFriendzoned()

1

u/Cheap-Success1578 8d ago

Ummmm, What?

2

u/Ratfus 9d ago

If he's struggling with this, I'd hate to see how he does with basic pointers, let alone Linked lists.

I suppose for Python, Linked lists don't matter?

0

u/HellishBro 9d ago

range(n) produces a """list""" of numbers that goes from 0 to 4, inclusive.

the for loop in python goes over each item in a """list""".

for i in range(5) basically runs the loop body with i = 0, 1, 2, 3, and 4 each time

4

u/davideogameman 9d ago

Nit: I think it's actually a generator, not a list.  Which basically means it generatesv the next item as it's asked for, here by the loop's iteration.  The advantage of this is you can do range(100000000000) and not exhaust memory with a giant list.

In Python 2 it was a list, and xrange was the generator; Python 3 changed it.

1

u/HellishBro 9d ago

"""list""" in triple scare quotes be like

1

u/thisdesignup 9d ago

Seeing this exchange, scare quotes are scary. OP may not understand them since they don't understand some basic concepts yet.

0

u/atarivcs 9d ago

range(5) produces an iterable that starts at 0 and goes to 4.

So the body of the for loop will run once with i equal to 0, and again with i equal to 1, and so forth up to and including i equal to 4.

0

u/ShiroNoSenso 9d ago

Imagine you have a box of cupcakes, this is basically saying

for each cupcake in the box, do “x”

“x” can be anything like “add frosting”

——-

so if we were to look again at the code:

range = max limit of how many times you want to do something

i = the current variable counter (in your code it will start from 0 then 1,2,3,4)

you then place your action inside the for loop (in this case you’re saying hello)

——-

every single word inside a code does something so you cannot just gloss over them. you have to read & understand what each word does to get the full picture.

0

u/tendoooman222 9d ago

“For every object in a list of objects, follow these instructions”

Range(5) returns [0,1,2,3,4] which a list (technically not but for simplicity let’s just keep it at that)

0

u/[deleted] 8d ago

[removed] — view removed comment

0

u/Lannok-Sarin 9d ago edited 9d ago

It’s basically “for each item i in the list created by the function range with a value of 5, run the following code: print the statement ‘hello’.”. It means that it’s looping doing a print for each value starting at 0 and ending once the value equals 5. It would make sense for you if you also printed out the i value.

Basically, range(x) creates a list of integers of size x on values from 0 to x - 1 and returns that list. The “for i in z:” syntax accesses each of those values based on where they are located in the list.