Reversing a list in Python -


def manualreverse(list):     return list[::-1]      def reverse(list):         return list(reversed(list))     list = [2,3,5,7,9]  print manualreverse(list) print reverse(list) 

i started learning python. can me below questions?

1.how come list[::-1] returns reversed list?

2.why second function throw me nameerror: name 'reverse' not defined?

[::-1] equivalent [::1], instead of going left right, negative makes go right left. negative step of one, returns elements in opposite order. whole syntax called python slice notation.

the reason why 'reverse' not defined because did not globally define it. local name in manualreverse function. can un-indent function global function.

def manualreverse(list):     return list[::-1]  def reverse(list):     return list(reversed(list))    

by way, it's never idea name lists list. override built-in type, including function too, depend on ( list(reversed(list)) )


Comments