Monday, August 10, 2009

Slicing in Python

Python supports slicing of sequences. Just watched a video on Python slicing here.

My notes follow:

Slicing a sequence is the act of taking a sequence and getting back some elements from it. These elements couls be consecutive elements or they could be spaced at an interval.

Let's create a list and then slice it

my_list = [2,3,4,5,6,7,8,9,]

print my_list[2:7]
Will return all elements from the 2nd to the (7-1)st position.
[4, 5, 6, 7, 8]


print my_list[2:]
Will print all elements from the 2nd element to the end of the list.
[4, 5, 6, 7, 8, 9]


We need not get only consecutive elements. They can also be spaced.
print my_list[2:7:2]
Will print elements spaced at a distance of 2 from the 2nd element to the 6th element.
[4, 6, 8]


We can also address the list using -ve indexes.
print my_list[-5:-1]
Will return all the elements starting from the 5th element from the end going upto the element before the 1st element from the end.
[5, 6, 7, 8]


If we want to print from the 5th element from the end to the last element, we need to use
print[-5:]
[5, 6, 7, 8, 9]


Lists using -ve indexes can also be spaced.
print my_list[-5:-1:2]
[5, 7]

No comments: