How should I read `for i in range(5)` in plain English?
Asked by
MellowPine42
I'm learning the basics of Python and come from a non-technical background. I understand that this code prints "hello" five times, but I'm confused by how to read the first line as an English sentence:
for i in range(5):
print("hello")
What exactly is `for i in range(x)` saying? Is it saying "repeat this five times," or "for each value in a range, assign that value to `i`"? I'm looking for a simple, one-sentence explanation of what this syntax means.
Answers
You can mentally expand the line like this:
`for i in range(5):`
becomes roughly:
`for i in [0, 1, 2, 3, 4]:`
In other words: โFor `i` equal to each of 0, 1, 2, 3, and 4, run the indented code.โ Technically, `range(5)` creates an iterable rather than an ordinary list, but it behaves this way for understanding the loop. Also, the upper limit is not included, which is why 5 itself is not assigned to `i`.
Reply to this answer
Think of the pattern as:
`for item in collection:`
`do something with item`
For example, `for fruit in ["apple", "banana"]:` means โtake each fruit from this collection, one at a time, and run the indented code.โ In your example, `i` is just the variable name, and `range(5)` supplies five values: 0 through 4.
Reply to this answer
A simple way to say it is: **โFor each value produced by `range(5)`, put that value into `i` and run the indented code.โ**
`range(5)` represents the values 0, 1, 2, 3, and 4. The loop runs once with `i` equal to 0, then again with `i` equal to 1, and so on. Since the code inside the loop never uses `i`, it simply prints `"hello"` five times.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowPine42: That helps. So `i` is not the instruction to repeat something; it is the name given to the current value during each pass through the loop.