A list and range() question (ex32)

Hey,
been messing with ex32 of the book and doing some experiments when I stumbled upon something I couldn’t understand.

Was tryna see what would happen if I type:

>>> for elements in range(0, 6):
        print("Hello")

Which it gave me:

Hello
Hello
Hello
Hello
Hello
Hello

I thought range(n, m) applies to n until m-1 so why did it loop 6 times.

Then I tried printing elements:

>>> print(elements)
5

then it returned a 5? and it had nothing to do with the positions in elements (since I tried appending to elements and got an error:

AttributeError: 'int' object has no attribute 'append'

so now elements isn’t a list and it’s an integer? and 5 at that when the code looped it 6 times?

I thought the range function returns a sequence of numbers not an int, and the list just turned into a int?? Why did it loop “Hello” in the first place if it’s an int??

I’m just sorta confusion here and I know I sorta did a mish-mash out of everything and probably shouldn’t have even typed:

>>> for elements in range(0, 6):
        print("Hello")

in the first place but now I’m curious and need answers so I would really appreciate anyone’s help on the matter.

Anyway thanks for the read :slight_smile:

Range is zero-based and up to upper limiter, so range(0,6) is 0,1,2,3,4,5 (requiring 6 loops).

The print(elements) returning 5 is curious. Have you got this as a variable or running straight after the loop?

Edit: I see now.

Try this to get your answer…

for elements in range(5,11):
    print(elements)

5
6
7
8
9
10

print(elements)
10
3 Likes

Just to expand on @gpkesley’s answer:

range returns some sort of a generator, that is, a machine that spills out an int whenever you push a button. The for-loop repeatedly pushes the button and assigns the int to its variable. You just didn’t do anything with that variable in the body of the loop.

There’s nothing wrong with what you wrote. It’s actually pretty common to write this if you need to do something a specific number of times. You just do for _ in range(x) and Python will do whatever you want x times.

1 Like

I’ve looked into this a bit more as I’ve never actually printed the ‘index variable’ from a loop before. Well, not that I am aware of. I found this example interesting, as its all scope related.

https://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/

I never really do:

for i in range(4):
    d = i * 2
print(d)

I’ve always actioned in the block of the loop:

for i in range(4):
    d = i * 2
    print(d)

So I’ve never had my attention to draw to this scope situation before.

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.