List Slicing Python?


#1

[[[[[[ INSTRUCTIONS ]]]]]]]]
On line 4, create a list called middle containing only the two middle items from suitcase.
On line 5, create a list called last made up only of the last two items from suitcase.

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

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

question;
why is it that (( middle )) is [2:4] instead of [2:3]?

Same thing goes for (( last)) [4:6] should be 4:5?


#2

@majinzo,

You could imagine the usage
suitcase[2:4]
as being a short-cut-writing of a FOR-loop
=begin at item-nr 2=
upontill
=item-nr less than 4=


#3

Hi @majinzo ,

Notice that in Exercise 5: List Slicing, the background information includes this:

Then, we take a subsection and store it in the slice list. We start at the index before the colon and continue up to but not including the index after the colon.

Based on that explanation, you need ...

middle = suitcase[2:4]

... because 4 is the next index after index 3, which is the last index that is included in the slice.


#4

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

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)
print suitcase
print first
print middle
print last


#5

What’s the difference between

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
# Why use this solution
first = suitcase[0:2]
middle = suitcase[2:4]
last =  suitcase[4:]
# Rather then this solution
slice = suitcase[1:5]

print suitcase
print first
print middle
print last
print slice

Is there a reason to create a variable rather then the slice function?