La Boina Roja

The struggles off a future RHCE….

Slicing in Python

Leave a comment

sword

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  photo piangry.gif 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!

lenismean

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  photo emo.gif ), 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  photo piwink.gif to slice the first  two items (“Master Chief”, “James”).

first_two

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  photo redface.gif

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:]

listai

Remember slicing does not affect the original list! originallist

(You can always do the cliccy for a larger piccie!)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s