reverse() usage in python?

2019-08-05 18:27发布

The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

The above text can be found at http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types

What does "modify the list in place for economy of space" mean?

Example:

x = ["happy", "sad"]
y = x.reverse()

would return None to y. So then why does,

x.reverse()

Successfully reverse x?

3条回答
贪生不怕死
2楼-- · 2019-08-05 18:57

list.reverse reverses the list in-place and returns None, it's designed to do so, similar to append, remove, extend, insert, etc.

In [771]: x = ["happy", "sad"]

In [772]: x.reverse()

In [773]: x
Out[773]: ['sad', 'happy']
查看更多
可以哭但决不认输i
3楼-- · 2019-08-05 19:11

What does "modify the list in place for economy of space" mean?

What this means is that it does not create a copy of the list.

why does, x.reverse() Successfully reverse x?

I don't understand this question. It does this because that's what it's designed to do (reverse x and return None).

Note that sort() and reverse() have counterparts that don't modify the original and return a copy. These functions are called sorted() and reversed():

In [7]: x = [1, 2, 3]

In [8]: y = list(reversed(x))

In [9]: x
Out[9]: [1, 2, 3]

In [10]: y
Out[10]: [3, 2, 1]
查看更多
欢心
4楼-- · 2019-08-05 19:18

In almost any programming language there are two kinds of callable definitions: functions and procedures.

Functions are methods or subroutines that do some processing and return a value. For instance, a function to sum two integers a and b will return the result of the sum a + b.

In the other hand, procedures are pretty much the same (even in the syntax in most languages) with the slight difference that don't return a value, and of course they are used by their side effects, meaning that they change the state of something or just process some data and save it or just print it out to a file.

So in this case, reverse would act as a procedure, which changes the state of the list being reversed (by reversing it), and here is how this can be done without extra space:

def reverse(l):
    for i in range(len(l) / 2):
        l[i], l[-i-1] = l[-i-1], l[i]

Notice that a new list is never created, instead, what the code does is to interchange the elements of the list l in place by swapping the first and the last, the second and the penultimate and so on until the element in the half of the list.

Hope this helps you understand ;)

查看更多
登录 后发表回答