简体   繁体   中英

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 ?

[::-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)) )

list[::-1] utilizes a slice notation and returns all the elements but in reversed order. Explain Python's slice notation Here is a detailed explanation with examples - it will answer this and more similar questions.

Indentation of def reverse(list) makes it visible only inside manualReverse(list) . If You unindent it will become visible globally.

Simply use the builtin function reversed

>>> reversed(my_list)

See http://docs.python.org/2/library/functions.html?highlight=reversed#reversed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM