## 2.3.3 list method

catalogue

Next section: tuples and summary

### 8. reverse

The reserve method stores the elements in the list in reverse

>>> x = [1,2,3] >>> x.reverse() >>> x [3, 2, 1]

Ps: this method also changes the list but does not return a value (like remove and sort, currently only pop() returns a value)

Tip: if you need to reverse iterate a sequence, you can use the reversed function. This function does not return a list, but an iterator object. Nevertheless, it is feasible to use the list function to convert the returned object into a list.

>>> x = [1,2,3] >>> list(reversed(x)) [3, 2, 1]

If x.reversed(): an error is reported

>>> reversed(x) <listreverseiterator object at 0x7ff33650e450> #Returns an iterator object listtraverseterator

### 9. sort

The Sort method is used to Sort the list in its original location. Sorting in place means changing the original list so that the elements can be arranged in a certain order, rather than simply returning a copy of the sorted list.

>>> x = [4,6,2,1,7,9] >>> x.sort() >>> x [1, 2, 4, 6, 7, 9]

The previous methods such as append, insert and remove that do not return values are reasonable in most cases. However, this behavior of the sort method should be explained in detail, because many people are confused by the sort method: when users need a copy of the ordered list and keep the original list unchanged, problems arise. In order to realize this function, we naturally think of the following practices (actually wrong)

>>> x = [4,6,2,1,7,9] >>> y = x.sort() #Don't do this! >>> print y None

Because the sort method modifies x but returns a null value, the sorted X and y with the value of None are finally obtained.

The same is true for reverse, remove, append, insert and other methods, because they do not return values. So far, except pop, the pop() method will return the removed values, as follows:

>>> x = [4,6,2,1,7,9] >>> y = x.pop() >>> print y 9 >>> print x [4, 6, 2, 1, 7]

The correct way to achieve the above functions is to assign a copy of x to y, and then sort y.

>>> x = [4,6,2,1,7,9] >>> y = x[:] >>> y.sort() >>> x [4, 6, 2, 1, 7, 9] >>> y [1, 2, 4, 6, 7, 9]

In this place, I wonder why y=x [:] is not directly y=x

>>> x = [4,6,2,1,7,9] >>> y =x >>> x [4, 6, 2, 1, 7, 9] >>> y [4, 6, 2, 1, 7, 9] >>> print y [4, 6, 2, 1, 7, 9]

After my operation, it is clear that the value of X is directly given to y, and the return is also a list; Fortunately, the following book says this: calling x [:] again will get a fragment containing all the elements of X. This is a very efficient method to copy the whole list. It's no use simply copying x to y. Because doing so makes X and Y point to the same list.

>>> x = [4,6,2,1,7,9] >>> y = x >>> y.sort() >>> x [1, 2, 4, 6, 7, 9] #x is also sorted >>> y [1, 2, 4, 6, 7, 9]

Another way to get a copy of a sorted list is to use the sorted function:

>>> x = [4,6,2,1,7,9] >>> y = sorted(x) >>> x [4, 6, 2, 1, 7, 9] >>> y [1, 2, 4, 6, 7, 9]

This function can be used for virtually any sequence, but always returns a list.

Ps: the return value of pop() learned so far, and sorted returns a sorted list.

>>> sorted('Python') ['P', 'h', 'n', 'o', 't', 'y'] >>> sort('Python') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sort' is not defined

If you want to arrange some elements in reverse order, you can first use sort (or sorted) and then use the reverse method. Alternatively, you can use the reverse parameter, which is described in the next section.

PS: note that you need to call the sort method and the reverse method on the list twice. If you intend to implement it through x.sort().reverse(), it will not work, because x.sort() returns None. Of course, sorted(x).reverse() is the correct way, because sorted() will return a list.

### 10. Advanced sorting

If you want to sort in a specific way (instead of the default way of the sort function, that is, the elements are sorted in ascending order according to the python default sorting rules, which will be described in Chapter 5), you can customize the comparison function in the form of compare(x,y). The compare(x,y) function returns a negative number when x < y and an integer when x > y. If x=y, it returns 0 (according to customization). After the function is defined, it can be provided to the sort method as a parameter. The built-in function cmp provides the default implementation of the comparison function:

>>> cmp(42,32) 1 >>> cmp(99,100) -1 >>> cmp(10,10) 0 >>> numbers = [5,2,9,7] >>> numbers.sort(cmp) #cmp >>> numbers [2, 5, 7, 9]

The sort method has two other optional parameters - key and reverse. To use them, you need to specify them by name (this is called keyword parameters, Chapter 6). The parameter key is similar to the parameter cmp - a function used in sorting must be provided. However, this function is not directly used to determine the size of the object, but creates a key for each element, and then all elements are sorted according to the key. Therefore, if you want to sort by the length of the elements, you can use len as the key function.

>>> x = ['aardvark','abalone','acme','add','aerate'] >>> x.sort(key=len) >>> x ['add', 'acme', 'aerate', 'abalone', 'aardvark']

Try the default sorting method

>>> x = ['aardvark','abalone','acme','add','aerate'] >>> x.sort() >>> x ['aardvark', 'abalone', 'acme', 'add', 'aerate'] #The findings are in alphabetical order

Another keyword parameter, reverse, is a simple Boolean value (True or False, which will be described in more detail in Chapter 5). Used to indicate whether the list should be sorted in reverse.

>>> x = [4,6,2,1,7,9] >>> x.sort(reverse=True) #True reverse, False does not use reverse >>> x [9, 7, 6, 4, 2, 1]

cmp, key and reverse parameters can all be used in the sorted function.