Omitting indices 8/18


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!


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:


so the general syntax is:


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:


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


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


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