reversal of collections can be coded either recursively or iteratively in pythonand as functions or class methods example - is first attempt at two simple reversal functions example - pp \dstruct\classics\rev py def reverse(list)recursive if list =[]return [elsereturn reverse(list[ :]list[: def ireverse(list)iterative res [for in listres [xres return res both reversal functions work correctly on lists but if we try reversing nonlist sequences (stringstuplesand so on)the ireverse function always returns list for the result regardless of the type of sequence passedireverse("spam"[' '' '' '' 'much worsethe recursive reverse version won' work at all for nonlists--it gets stuck in an infinite loop the reason is subtlewhen reverse reaches the empty string ("")it' not equal to the empty list ([])so the else clause is selected but slicing an empty sequence returns another empty sequence (indexes are scaled)the else clause recurs again with an empty sequencewithout raising an exception the net effect is that this function gets stuck in loopcalling itself over and over again until python runs out of memory the versions in example - fix both problems by using generic sequence handling techniques much like that of the prior section' permutation utilitiesreverse uses the not operator to detect the end of the sequence and returns the empty sequence itselfrather than an empty list constant since the empty sequence is the type of the original argumentthe operation always builds the correct type sequence as the recursion unfolds ireverse makes use of the fact that slicing sequence returns sequence of the same type it first initializes the result to the slice [: ] newempty slice of the argument' type laterit uses slicing to extract one-node sequences to add to the result' frontinstead of list constant example - pp \dstruct\classics\rev py def reverse(list)if not listreturn list data structures empty(not always []the same sequence type