Page 1 of 1

basic python question

Posted: Tue Nov 07, 2017 2:03 pm
by tony1812
Hello, I have a python array
array={1,2,3,4]

Now I like to retrieve the values in the array using for xxx in range (y)
for index in range(4):
print(array[index])
result: I get all 4 array values-1,2,3,4
but if I use
for index in range(3):
print(array[index])
result: I only get 3 array values-1,2,3
Does in range not start on index 0? Thanks.

Re: basic python question

Posted: Tue Nov 07, 2017 2:13 pm
by bensimmo
It ends at but does not include the last number, as such

So 4 = 0,1,2,3 (four in total)


It's a bugger and an English Vs Computer thinking.
Python didn't move the Computer part into the background ;-)

Re: basic python question

Posted: Tue Nov 07, 2017 3:56 pm
by pcmanbob
Tony.

I thing your confusion is with what's being returned and how the count is done.

run this simple program

Code: Select all

items = [1,2,3,4]

for index in range(len(items)):
    print(index, items[index])
    
and you get this as the result

Code: Select all

(0, 1)
(1, 2)
(2, 3)
(3, 4)
So the number on the left is the actual counting loop which starts at zero but it returns the first number in your array which is of course one and so on
till we get to the last number which is 3 in the loop but it returns 4 as it's the last number in the array.

So if we change the array to this

Code: Select all

items = [11,23,63,84]
We get this as the result which might make things a bit clearer.

Code: Select all

(0, 11)
(1, 23)
(2, 63)
(3, 84)

Re: basic python question

Posted: Tue Nov 07, 2017 4:03 pm
by jahboater
bensimmo wrote:
Tue Nov 07, 2017 2:13 pm
It ends at but does not include the last number, as such

So 4 = 0,1,2,3 (four in total)


It's a bugger and an English Vs Computer thinking.
Python didn't move the Computer part into the background ;-)
The language B (precursor to C) did that (arrays started at one instead of zero) by adding an extra item at the start that was never used.

The other possibility is continually subtracting one on every single array reference.

Both are horrible!

Re: basic python question

Posted: Thu Nov 09, 2017 7:55 pm
by robbes
Only slightly off-topic:
The enumerate method provides an option for you to specify the starting value of the index in an enumerated list.
For example, to have the first value of the index as 1 rather than the default 0:

Code: Select all

mylist = [2, 4, 6, 8]
for index, item in enumerate(mylist, 1):
    print(index, item)

Re: basic python question

Posted: Tue Nov 21, 2017 7:01 pm
by bb677a
Your main issue is not using the range function correctly. You are only asking for 3 numbers, see below results. Replace that '3'in your code with a '4' and you should get what you want.

Code: Select all

>>> for index in range(3):
	print index

	
0
1
2