Reverse string and list



How to reverse Reverse string in python ?

>>> python = "love you python"

>>> python[::-1]
'nohtyp uoy evol'

How to access list in reverse order ?

User builtin function reversed()
Can be used for strings also.
reversed() will return you generator object, to access objects in it user next()

eg:
>>> z = ["a","b","c","d"]
>>> y = reversed(z)
>>> y
<listreverseiterator object at 0xb764e82c>

>>> y.next()
'd'
>>> y.next()
'c'
>>> y.next()
'b'
>>> y.next()
'a'

List can be reversed in two ways either use builtin reversed() or Lists own method reverse()

>>> for i in reversed(["a", 3, "lo"]):
...     print i
...
lo
3
a

>>> z = ["a","b","c","d"]
>>> z.reverse()
>>> z
= ['d', 'c', 'b', 'a']


>>> for i in l.reverse():
...     print i
...
lo
3
a