Python array slice

Slicing a list (array) in python is very handy way to get a sub list of an array. Its syntax is

## slice from start till end-1 (in using step)
newlist = a[start:end:step]

Here are some use cases.

create new list taking first 2 items

a = ["v1", "v2", "v3", "v4", "v5"]
new = a[0:2]
print new
['v1', 'v2']
Env: Python 2.7.6

create new list taking 3rd and 4th items

a = ["v1", "v2", "v3", "v4", "v5"]
new = a[2:4]
print new
['v3', 'v4']
Env: Python 2.7.6

create new list taking last 2 items

a = ["v1", "v2", "v3", "v4", "v5"]
new = a[-2:]
print new
['v4', 'v5']
Env: Python 2.7.6

create new list taking everything except last 2 items

a = ["v1", "v2", "v3", "v4", "v5"]
## can also use a[0:-2]
new = a[:-2]
print new
['v1', 'v2', 'v3']
Env: Python 2.7.6

create new list taking all even items

a = ["v1", "v2", "v3", "v4", "v5"]
new = a[1::2]
print new
['v2', 'v4']
Env: Python 2.7.6

create new list taking all items

This will copy list to a new list.

a = ["v1", "v2", "v3", "v4", "v5"]
new = a[:]
print new
['v1', 'v2', 'v3', 'v4', 'v5']
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments