Omitting indices 8/18


#1

my_list = range(1, 11)
print my_list[::2]

So I ended up at this exercise and I don’t now how honestly. Why does this print [1, 3, 5, 7, 9]. I would think that my code would print only the first 3 characters of the range (1,11) so that would be 1,2,3. Can somebody explain to me what is happening here? Thanks!


#2

that would be [:2], that would give you indexes 0 and 1, so values 1 and 2 of my_list

[::2] has two colons, the third value of list slicing is step, so how much the counter should increase. We can add the other values to make it clearer:

[0:len(my_list):2]

so the general syntax is:

[start:stop:step]

start value is inclusive, stop value is exclusive. so its values lesser then (<) then the stop value, not lesser or equal to (<=).

we could have just provided steps to range as well:

range(1,11,2)

but i guess teaching a concept goes first in a codecademy exercise


#3

Thank you very much, especially for the last line of your comment :wink:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.