First page Back Continue Last page Overview Graphics

Reversing a List

Exercise:

Figure out a way to reverse a list by using append and pop.

def rev(lst):

revl = []

while (lst):

el = lst.pop()

revl.append(el)

return revl

MyList = ["a","b","c","d"]

MyList = rev(MyList)

print(MyList)

The function rev() returns a list in reverse sequence:

$ python3 reverse.py

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

The easy way:

>>> simpsons = ["Lisa","Homer","Bart","Maggie","Marge"]

>>> simpsons.reverse()

>>> simpsons

['Marge', 'Maggie', 'Bart', 'Homer', 'Lisa']