List Slicing


#1



https://www.codecademy.com/courses/python-beginner-en-pwmb1/1/2?curriculum_id=4f89dab3d788890003000096#


According to the exercise hint:
In order to slice the last two items from the list:

myList = [0,1,2,3,4]

the ending index of your slice will be one beyond the actual last index of the list.

Therefore, if we wanted to slice the last two items from myList we would have to write something like

last_two = myList [3:5]

instead of

last_two = myList[3:4]


Could you please explain why it must be this way?
Cheers


Replace this line with your code.


#2

so list slice has two values:

[start:stop]

the stop value it self is not included, its values lesser then (<) the stop value, not lesser then or equal to (<=)

Why it is this way? Because the person who wrote python decided to implement it as such. In my opinion for good reason, if you want to use len():

myList = [0,1,2,3,4] 
last_two = myList [3:len(myList)]

the length is 5, so if the stop value was included, this would cause problems


#3

Thank you very much for the clarification :slight_smile:


#4

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