FAQ: Learn Python: Loops - Using Range in Loops

Community%20FAQs%20on%20Codecademy%20Exercises

This community-built FAQ covers the “Using Range in Loops” exercise from the lesson “Learn Python: Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Using Range in Loops

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

edit: I’ve read the previous post.
Sorry, still trying to learn how to navigate this forum.
Hi,
I am curious to know why Python creates a list in order to iterate n times.
Whereas In C-like languages for example, the For loop jumps to the address of the message n times.
Python:
for i in range(5):
print(promise)
C:
for(i=0;i<5;i++)
printf("%s",promise);

When I do this:

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

I get this output:

0
1
2
3
4

Why is that?
I can’t find the logic…

First we would want to ratify our understanding of range. When only a stop value is supplied, as given above, then the range begins on 0 and stops on 5 (the stop value given), but does not include it. Therefore the range list is, [0, 1, 2, 3, 4].

1 Like

this i get.
but why does it print the numbers, and not the string in the promise variable?

Given we are iterating a range, there are only numbers to print. promise is not a string, as such, but a reference to the current iteration value.

I think I didn’t fully understand your answer, since I’m still buffled:

Why then does it print the string when we type:

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

I would expect the same result as in the previous example.
perhaps my question should be:
When I name the items in the list ‘promise’ (same as the name of the variable with the string), the outcome is different than when i give them any other name.
why is that?

Perhaps there is a part of the lesson/exercise we are not seeing. In Python we can re-assign any type to a variable. The variable is like a tag hanging on a hook. To change the value, we simply move the tag to the new value, not change the value where the tag is hanging.

a =  "a string"
print (a)    #  a string

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

0
1
2
3
4

Note that a is no longer a string.

2 Likes

I finally get it!

this:

can be translated into:
for every item (called x here) in the list (called range(5)), print the string (called promise).

while this:

can be translated into:
for every item (called promise) in the list, print it.

a bit of an awkward explanation, but that’s how i think. in my head, before i wrote it, it looked simpler…

anyway, thank you very very much for your patience, mtf.

2 Likes

Why are we not converting object returned by range() function to list using list()?

We only need to cast a list if we wish to preserve the range in physical form. Otherwise we can just iterate the generated sequence and not use up any memory. A range object takes up practically no memory, no matter the range. A list object uses progressively more memory the larger it gets.

3 Likes

This was really confusing at first, but now I think that I understand. My code is:

promise = “I will not chew gum in class”
test = “What in the world is this.”
oh_wait = “Oh wait, I think I get it.”
for p in range(5):
-print(promise)
-print(test)
-print(oh_wait)

(the “-” represents one indentation in)

And then this text appeared on the screen five times:

I will not chew gum in class
What in the world is this.
Oh wait, I think I get it.

Am I understanding correctly, that we are simply creating a variable where p represents print, and then defining the behavior for any print calls one level in?

Will this affect other print calls later in the code, theoretically?

I’m still learning the vocab here, which is probably apparent with the way I phrased my question, so if anyone could clarify and also correct my vocab, that would be super helpful to me. Thanks!

Welcome to the forums!

No. Yes, p is a variable, but it does not represent the print() function.


for p in range(5):

This line declares a for loop where p will be the next element in the iterable range(5) each iteration. Now to explain those words used in the previous sentence, an iteration is one loop. Once the code inside the loop has been executed once, we say that one iteration has been completed and we move back to the beginning of the loop to iterate over it again until, in the case of for loops, we have iterated through every item in a sequence. An iterable is something that can be iterated over, like a list (where we iterate through each of the elements), a dictionary (iterating over each of the keys), etc.

range(5) is an iterable. range(5) creates a range object, which is a sequence of integers. These integers are different depending on the argument(s) you pass to range(). In the case of range(5), if you were to represent it as a list, it would be [0, 1, 2, 3, 4]. Learn more about range() here. Each iteration, we assign p the value of the next item in range(5). So, the first iteration, p = 0, the second iteration, p = 1, the third iteration, p = 2, the fourth iteration, p = 3, and the fifth iteration, p = 4. At this point, we have iterated through all the items in range(5) and so the for loop ends. The following example illustrates this.

>>> for p in range(5):
...   print(p)
... 
0
1
2
3
4

Since your code doesn’t actually use p in the code block indented inside the for loop, think of this loop as one that executes all the statements that are indented inside the loop 5 times. It is 5 times because p will be assigned a different value in range(5) a total of 5 times.


Side note: please format your code using the </> button in future posts (this preserves indentation).

Thanks MTF, that makes sense. In this lesson however we have the following:

Notice that we need to iterate through a list of length 3, but we don’t care what’s in the list. To create these lists of length n , we can use the range function. range takes in a number n as input, and returns a list from 0 to n-1 . For example:

```
zero_thru_five = range(6)
# zero_thru_five is now [0, 1, 2, 3, 4, 5]
zero_thru_one = range(2)
# zero_thru_one is now [0, 1]
`
This does not seem correct, and if I print(zero_thru_five) after running that I get range(6) not [0,1,2,3,4,5]. Is this because it is python3 and the lesson was written for python2?

It may be that the narrative wasn’t altered with the transitioning of the old lesson to the new Pro LE. In Python 3 range() does not return a list, but a range object, hence, range(6).

The range is still iterable, of course, but needs to be cast to a list or some other sequence to be readable. Unlike iterators, range is not consumed so can be referred to multiple times.


Sidebar

Even while a range object takes a fixed amount of memory regardless how extensive the range, we’ve seen that a list will iterate faster than the range object. If dealing with a large expanse, it might be worth the memory hit to convert to a list or tuple before iterating. A case by case basis, only. For small ranges I’d go with the least memory option.

this helps man, thank you!

I just want to make sure that I understand how the format for loops in Python with the “for” iteration works.

If I want to list all elements of a list (one by one), I can use the “for” loop with the following format:

for any_variable_which_I_can_name in list_that_I_am_interested_in_writing_out_each_item:

print(any_variable_which_I_can_name)

This format above will always work any time I want to print out the items of a list one by one as they appear sequentially on a list.

If I want to print a certain element/message N number of time, I would be using the “for” loop with a range()

message = “xyz”
for completely_unrelated_variable_to_the_above_one in range(N):

print(message)

I would also want to verify that I understand the following:

The reason that the following:

message = “xyz”
for message in range (N)

print(message)

Would give:

0
1
2
3
4
.
.
.
N-1

If because, the above loop updates the value of the variable “message” to be the value of the value assigned in range(N), hence why the number 0 to N-1 appear, instead of “xyz” repeated N-1 times.

The variable we use in our signature line is intentionally discrete. With some experimentation we can observe what happens with your code, above.

>>> message = "xyz"
>>> n = 5
>>> for message in range (n):
        print(message)

        
0
1
2
3
4
>>> message
4
>>> 

In other words, there is no, “xyz”.


>>> message = "xyz"
>>> for n in message:
        print (n)

        
x
y
z
>>> message
'xyz'
>>> 

board_games = [“Settlers of Catan”, “Carcassone”, “Power Grid”, “Agricola”, “Scrabble”]

for game in board_games:
print(game)
to clarify here:

game is used to identify the loop as a temporary variable?

It doesn’t identify the loop per se but it is the name to which elements from the iterable you have chosen to iterate through are assigned.

It behaves more like the following-

# first iteraton
name = board_game[0]
# next iteration
name = board_game[1]
... # and so on

On each iteration an element from that list (selected in order) is assigned to the name game. So on the first iteration “Settlers of Catan” is assigned to game, once the suite of code marked by indentation has finished the next iteration starts and the next element is assigned to game.

At the end of the loop game is still a valid name and would be assigned to the last element of that list (so it’s not a true temporary variable like in some languages; loops in Python do not have their own scope).