Python List Slicing (Indexing)

0
1323
Python List Slicing and Indexing

BASIC PYTHON LIST SLICING (INDEXING)

Given that there can be many items in a list there can be some instance where you want to extract only certain items.

This is what’s called as Python list slicing.

To be able to slice, one must familiarize first with the concept of indexing.

In Python every item in a list is indexed with a certain number. Indexing starts from 0 which is different from other programming language. Let’s create a list with each items corresponding to its index.

mylistindex = [0, 1, 2, 3, 4, 5]

Here you can see that the first item is indexed as 0. While the last item is indexed as 5 although we have 6 items in the list.

So let’s begin Python list slicing.

To select a single item we use [] after the list name. So for example if we want to get the first item.

Input:

mylistindex = [0, 1, 2, 3, 4, 5]

mylistindex[0]

Output:

0

If we want to get the third item.

Input:

mylistindex[2]

Output:

2

MULTIPLE ITEMS PYTHON SLICING (INDEXING)

To select multiple items in Python the colon : is used. This is used in combination with the bracket [:].

Say we want to select only the first three items.

Input:

list = ['a','b','c','d']

list[0:3] #can also be written as [:3]

Output:

['a','b','c']

Why is the indexing [0:3] rather than [0:2]?

It is because the code interprets it as SELECT ALL FROM 0 UP TO 3. This excludes index 3.

The code is [beg(included):end(excluded)].

The following example shows how to select all items in a list.

Input:

list[:]

Output:

['a','b','c','d']

To select all items from item 2 all the way to the end.

Input:

list[1:]

Output:

['b','c','d']

You can also use negative indexing when slicing. The negative indexing can be shown by the following example:

Input:

negindexing= [-4,-3,-2,-1]

negindexing[-3:-1]

Output:

[-3,-2]

PYTHON SLICING (INDEXING) STEP SIZE

If you want the selection to skip certain items via a pattern, you introduce step. This is an additional colon : in the bracket. [::]

So for example to select every other item.

Input:

list = ['a','b','c','d','e']

list[::2]

Output:

['a', 'c', 'e']

I would suggest that you experiment on your own with the indexing including step.

For more information go to the Python official documentation:

https://docs.python.org/2.3/whatsnew/section-slices.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here