List Slicing


#1

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 [3:4] # The last two items (index four and five)


#2

list slicing doesn't include the stop value. So [2:3] will give you the third item (second index). That is it, if you also want index 3, the stop value should be 4


#3

Rule no 1.
Indexing of list (or tuple or string) items always starts with 0.

Rule 2.

When we slice a list...say

x = [1,2,3,4]

print x[0:3]  # it will print [1,2,3]

It means that we are slicing from (3 items from list of index 0,1 and 2 excluding 3)

so youre making mistake in here..

middle = suitcase [2:3] # Third and fourth items (index two and three)
last = suitcase [3:4] # The last two items (index four and five)

Try to use the concepts described above!


#4

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