11 Apr 2013

Reverse in python


Reverse using reversed(seq) function
To reverse a sequence one can use the reversed(seq) built-in-function. what is sequence ? str, list and tuple are sequence. This function can take a sequence as a argument and returns an iterator. Lets dig deep into it.
reversed(seq) method will call the __reversed__() method of sequence which will reverse the elements of sequence and  and return a iterator for reverse sequence. So the reversed(seq) not just return a iterator but a reverse iterator.
 Feel from example:
>>list=[1,2,3,4,5]
>>reverse_iterator =  reversed(list)
>>for ele in reverse_iterator:
>>....    print ele                         // 5,4,3,2,1


We can also use the next() method of reverse_iterator object to call 'successive' elements.
>>reverse_iterator.next()         //5
>>reverse_iterator.next()         //4
>>reverse_iterator.next()         //3
>>reverse_iterator.next()         //2
>>reverse_iterator.next()         //1
>>reverse_iterator.next()         //StopIteration exception, since no more elements are left


Reverse using extended slice, [start:end:step]
Extended slice is another way to reverse str, list and tuple. First, lets get familiar with what extended slice is all about.  
Sometimes it may be desirable to iterate over only certain elements of a type. for example,
L = [11 22, 33, 44, 55, 66, 77, 88, 99, 100] , it may be required that one wants to iterate over only even or odd numbers thereby skipping certain elements from the list.
>>L = [11 22, 33, 44, 55, 66, 77, 88, 99, 100]
>>L[1:10:2]       -----> 2,4,6,8,10     // all even numbers of L
>>L[0:10:2]       ------> 1,3,5,7,9      // all odd numbers of L

Now let answer,  how ?
Syntax for extended slice is [start:end:step]. start specifies the index (of first element) from which it will start picking the elements, end specifies upto which index (of last element) it will pick elements and step specifies the number of elements to skip.

The default value of start is 0, of end is length of item in used ( length of L) and of step is 1.
So if you try like L[::] it will print the L as it is, assuming it as L[0:10:1]
Note that the step cannot be 0  because you have to take step to iterate (i made that up ). Therefore following will give error.
>>> L[0:10:0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: slice step cannot be zero




Here is important thing, the step part also defines the order in which an item is iterated. if you provide a negative value then it start iterating in reverse order.
>>> L[::-1]
[100, 99, 88, 77, 66, 55, 44, 33, 22, 11]

what L[::-1] means ?
It means that Iterate over L from 0 to length of L in reverse order.

So that all about reverse in python, i hope you find it useful.

No comments:

Post a Comment