Ha! Another trickety trick that is used on Python newbies is slicing. The trick is in getting the correct characters(in case of a string) or the correct items(in case of a list). They often make your mind boggle by asking you first to use len() to check the length of a list(or string).
Let’s say you have this list:
the_list = [“Master Chief”, “James”, “Miranda Keys”, “Cortana”, “343 Guilty Spark”, “Deja”]
As you know, that even though there are 6 items in the list but Python will only index 5 items. That’s because Python starts indexing from 0. Don’t be fooled by len(), however!
As you can see len() returned 6, this is what makes slicing so tricky!
Always remember:
“Python counts from 1, but indexes from 0.”
And of course there is another thing to keep in mind( you really didn’t think it would be that easy right ), in case of slicing Python will always returns the before last index.
So if you would like to get a slice containing only the first two items, you should type this:
first_two = the_list[:2]
Why didn’t I type the 0? When your slice needs to have the first item in it there is no need to type the 0, you can do it though if you want.
Check the following screen shot where I’m attempting to slice the first two items (“Master Chief”, “James”).
Now, you know Python always returns the before last index. The next question will be to include the last item in your slice. Now what
You get the last item by typing the index of the first item you want and leave the space after the colon blank.(In this specific case we are talking about the 5th index, which happens to be the 6th item.) It looks like this:
ai = the_list[3:]
(You can always do the cliccy for a larger piccie!)