theJava
theJava

Reputation: 15034

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?

Upvotes: 2

Views: 1688

Answers (3)

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13773

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.

Upvotes: 2

P. M.
P. M.

Reputation: 79

Simply use the builtin function reversed

>>> reversed(my_list)

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

Upvotes: 0

TerryA
TerryA

Reputation: 59974

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

Upvotes: 13

Related Questions