List slicing


#1



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


It says code gives back "passport" but not "passport" and "laptop". Can you see a bug ?


suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

first  = suitcase[0:2]  # The first and second items (index zero and one)
middle = suitcase[2:3]                # Third and fourth items (index two and three)
last   = suitcase[4:5]                # The last two items (index four and five)


#2

Never mind. Sorted. ...


#3

how did you it Mark I have the same issue


#4

I think they have a minor bug in this exercise 'coz I got passed on this line:

middle = suitcase[2:4]

Reason for being is they're asking you to type index 2 and 3 into brackets but it doesn't work (but it should. Just make sense) so I shot into dark and typed 2 and 4 and passed ... get back to me if that worked for you too.


#5

it worked thanks a lot Mark. I was struggling here 30 mins )))


#6

yeah I know that very well lol ...


#7

Guys, you are learning python, a programming language. NEVER, EVER go on with a mistake you fixed by lack and you did not understand. I can see that you have no idea what you did wrong and what right, and you even think that right doesnt make sense... Make sure to READ all the instructions before doing the exercises

Now, the explanation. You assigned to "middle" the string or strings "suitcase[2:3]". The exercise asks you to get the third and fourth items. Now, sure, we count from 0, so third is 2, fourth is 3. That is correct, BUT, the list slicing gets the items from the first index given WITH the item on the first index given, BUT it stops at the second index given, without getting it's item.

That's why suitcase[2:3] only gives "passport", because the slicing stops right before the index given second(in this case, 3), so it's like just getting suitcase[2].


#8

Oh yeah slicing works differently. Didn't occur to me at that time. Thanks very much for explanation. And sorry. I can imagine how a pro can get mad when student does what I did.


#9

I'm glad this helped you


#10

If it asks for the first and second index, it'll be [1:3]
If it asks for the second and third index, it'll be [2:4]

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. Check it out:

myList[3:5]

Returns [3, 4]


#11

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