Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 just started learning Python. Can anyone help me with the below questions?

1.How come list[::-1] returns the reversed list?

2.Why does the second function throw me NameError: name 'reverse' is not defined?

like image 253
theJava Avatar asked Jul 07 '26 14:07

theJava


1 Answers

[::-1] is equivalent to [::1], but instead of going left to right, the negative makes it go right to left. With a negative step of one, this simply returns all the elements in the opposite order. The whole syntax is called the Python Slice Notation.

The reason why 'reverse' is not defined is because you did not globally define it. It is a local name in the manualReverse function. You can un-indent the function so it is a global function.

def manualReverse(list):
    return list[::-1]

def reverse(list):
    return list(reversed(list))   

By the way, it's never a good idea to name lists list. It will override the built-in type, including the function too, which you depend on ( list(reversed(list)) )

like image 57
TerryA Avatar answered Jul 09 '26 20:07

TerryA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!