5. List Slicing


#1

What is wrong with my code?

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)

print middle

print last

Error: Oops, try again. It looks like your middle slice is ["passport"] instead of ["passport", "laptop"].


#2

this line:

middle = suitcase[2:3]

you use 3. But this include all items before item at index 3, item at index 3 not include. You might want to change this to 4. Same for last.


#3

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

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


#4

As you may/should already know the index counting starts from 0, as such the items in your list have the following indexes:

sunglasses has index 0
hat has index 1
passport has index 2
laptop has index 3
suit has index 4
shoes has index 5

The theory for slicing states that it will use/assign the item from the first index you provided up to BUT NOT INCLUDING the second index. Having said this the code you wrote has the following meaning:

first = suitcase[0:2] - will provide you with the item at index 0 and index 1 as the theory states that index 2 WILL NOT be included => that first will have only sunglasses and hat

middle = suitcase[2:3] - will provide you with the items at index 2 and that's it as the theory states that index 3 WILL NOT be included => that first will have only passport. If you want to include the laptop, your code should look like this:
CORRECT:
middle = suitcase[2:4]

last = suitcase[4:5] - will provide you with item at index 4 and that's it as the theory states that index 5 WILL NOT be included => that last will have only the suit. If you want to include the shoes, your code should look like this:
CORRECT:
last = suitcase[4:6]
or a bit more advanced one
last = suitcase[len(suitcase)-2:len(suitcase)]

Hope my explanation helps. Happy programming mate


#5

thank you that really helps.