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!
“Python counts from 1, but indexes from 0.”
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.
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!)