Why use the range function to iterate a for loop for a specific count?

Question

This exercise uses a range() function to cause the for loop to iterate a specific number of times. Why can’t the number of times to iterate a for loop be specified without range()?

Answer

In Python, a for loop is intended to iterate over a collection of items, unlike other languages where it is tied to a variable which has an initial value, an increment, and a test for the final value. Since the for loop is expecting a collection or list to iterate over, the range() function is used to provide a list of numbers. This list of numbers is used to cause the for loop to iterate the desired number of times. It’s important to remember that the list generated by range() defaults from 0 to one less than the number specified.

The following example uses range() with a starting number of 1 to print the squares of the numbers 1 through 10.

for number in range(1,11):         
    print(number ** 2)             
14 Likes

It makes more intuitive sense to me when I rewrite it this way:

for output in range(1,11):         
  print(output ** 2)   
4 Likes

The range() function returns an iterator. There is no output, as you have intuited. Each iteration is a number so it makes sense to call the variable, number.

In Python 3 a range isn’t even a list, just a range, an object that knows where it starts, and where it ends, and it has a method to find the next number in the sequence.

32 Likes

I am a bit confused as to why we have to print the full message “I will not chew gum in class” even though we set it = to the variable “promise”. Is there a way to print the message without having to type it out when actioning print("")?

4 Likes

@cesararellano7696287, what exercise are you referring to? All you need to do is:

message =  “I will not chew gum in class” 
print(message)

That would, in general, be the preferred, or at the very least, equally acceptable, approach, but without the lesson to look at, I can’t say why it was rejected, if it was.

it seems that range can tell how many times to iterate (as in the “promise” example), but in the above example, range is returning a value that gets squared. Range can have 2 different purposes.

In the above example the number of iterations is ten. range has no other purpose but to supply the starting number, and the next one, and the next one, up to but not including 11. Expressed as a list, we have,

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

It is those values squared that are printed in a separate, independent step.

The sole purpose of range is generate sequences. They can have any starting value, any ending value, and be in either direction, positive or negative.

 list(range(2, 21, 2))

 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

 list(range(21, 0, -3))

 [21, 18, 15, 12, 9, 6, 3]

 list(range(10, -1, -1))

 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
15 Likes

promise = “I will not chew gum in class”

for promise in range(5):
print(“I will not chew gum in class”)

if promise is already a variable, why do we need to print the full statement? Can’t we just set the command to print(promise)?

2 Likes
(1) promise = “I will not chew gum in class”

(2) for promise in range(5):
(3)        print(“I will not chew gum in class”)

Line 1 assigns (binds) to the variable promise a certain string. ("I will not, etc…)
Line 2 reassigns promise to a different value, in this case, a sequence of values, the integers 0 through 4. The string is lost to Python, as it has been assigned to no other variable. As far as this code snippet is concerned, it does not exist.

Line 3 brings back the string, this time as the argument to a print() statement. Again, promise by now has nothing to do with it, being bound only to 0,1,2,3,4. With each loop, the same print() statement is called.

12 Likes

That makes sense! I didn’t realize we were reassigning the promise to a new value (range(5)). That cleared my confusion. Thank you your Patrickd314!!

3 Likes

From my understanding it is not necessary to assign the string “I will not chew gum in class” to the promise variable in the first place (line 1) in order for the loop to run.

  • List item Is this understanding correct?

  • List item If the variable is reassigned during the loop is it removed as a global variable?

2 Likes

why can’t i put the range variable as the temporary variable here, and write:
for promise in range(5):
print(promise)

Refer to the earlier post higher up in this topic…

Why use the range function to iterate a for loop for a specific count? - #8 by cesararellano7696287

Thanks @mtf. I tried giving hyperlink as you did though but couldn’t find my way around it. Big smiles

1 Like

1- what do you mean by saying range() return an iterator ? iteration is an action how could we return an action ? we say we iterate through items , and how we could return an iterator

2-when i print

print(range(4)) # we see this in console = range(0,4)

and when we use :

for i in range(4):
   # ....

how we use range without changing it to list ? why we don’t need use list here as without it it return something like this :

range(0,4)

which I don’t know what it is I didn’t saw something like this in any other languages

the miss understanding is about what exactly this in console is :

range(0,4) # when we use range(4)

why we pass it to list function and what happen inside it and return list

and why we don’t use list in for loop when we use range()

Because range is a class of immutable iteration object. A while back I posted this example…

>>> r = range(10)
>>> type (r)
<class 'range'>
>>> isinstance(r, range)
True
>>> len(r)
10
>>> hasattr(r, '__iter__')
True
>>> r
range(0, 10)
>>> list(r)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> tuple(r)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> set(r)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> 

The object has an __iter__ attribute, which is what makes it immediately iterable. To represent the full sequence we cast it to a list, tuple or set, as illustrated above.

3 Likes

can I see iter attribute codes ? I think I need to learn class in python to understand this . I understand what you are saying but most part of process is dark to me .

Is <class ‘range’> data type in python ?

Yes, as defined by its class definition. It’s not that important that we peek under the hood, but it can’t hurt, so long as we can piece together what we see. It is a giant rabbit hole for a learner so expect it to get more mysterious until you have more under your belt. For now, keep the focus on concepts and syntax so you don’t lose sight of the main objective: Using a programming language.


Edit

Not to mislead… Data type, no. Object type, yes.

3 Likes

from 3/11 range in loops, why is this only printing ‘promise’ and not the information tide to the variable?

promise = “I will not chew gum in class”

for i in range(5):

print(promise)

You want the print command to be inside the for loop.

Insert a tab before print and see the difference. Any command inside for loop if left unindented will not be executed as part of the loop

promise = “I will not chew gum in class”

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

2 Likes