Python Question?

techi3

In Runtime
Messages
119
Why does this start counting with 21? I understand that it's counting every fourth digit backward but I'm unsure why it starts with -21 :confused:

x = list(range(22))
for i in x[::-4]:
print i,
 
I'm not sure why it'd start there, let alone be negative. From what I've seen on line, you should be starting at 0 and be able to go up to 21. You should never see a 22 unless you seeded the range function with a -22 to start with.
 
Thank you. I'll tinker with it a little more to see if I can figure it out. This one prints the same result:

i = 0
x = list(range(0,22))
x.reverse()
while i <= 21:
print x
i += 4

both print: '21 17 13 9 5 1' in that order but i'm still confused why the first one starts with 21. If its range is '0-21' and I start counting backwards by four why is it starting with 21? I guess I'll be digging through 'Think Python' all day today.
 
So when you reverse the list, it the list will then be 21, 20, 19..., 0 Since that loop starts at index 0 that's why the second code set produces those results.

Why the first code set you gave is doing the same thing, that I'm not sure..
 
Back
Top Bottom