.. _ch03-python-lists: =============================================================== More examples on Python lists =============================================================== Let's continue to master more examples in Python lists in this section. So far, we have seen several basic examples of lists. In this section we study more advanced examples. Traversal, sort, sorted ------------------------------------------ Like in the string case, the most common way to traverse the elements of a list is with a ``for`` loop. There are useful ways to modify a list using ``sort`` and ``sorted``: .. literalinclude:: ./codes/examples/lists/cheese.py :language: python :linenos: The output from this routine looks like:: False False False cheddar brie gouda (1) array.sort() modifies the original array: input = ['cheddar', 'brie', 'gouda'] input after input.sort() = ['brie', 'cheddar', 'gouda'] (2) sorted(array) does not modify the original array: sorted(input)= ['brie', 'cheddar', 'gouda'] input = ['cheddar', 'brie', 'gouda'] (3) sorted(array,reverse=True) reverses the array: sorted(input,reverse=True)= ['gouda', 'cheddar', 'brie'] input= ['cheddar', 'brie', 'gouda'] .. note:: In the above example, in line 32, we used ``s_orig = list(s)``, rather than ``s_orig = s``. What is the difference between the two? Adding and deleting ------------------------------------------- We already saw how Python can add a new list element to the end of a list. First example uses ``append`` method:: >>> t=['a','b','c'] >>> t.append('d') >>> print t ['a', 'b', 'c', 'd'] .. note:: As shown in the example, ``append`` method modifies the list in-place. If you do the following you will get an unexpected answer:: >>> t = t.append('d') >>> print t None This happens because all list methods are *void*, meaning that they modify the list and return ``None`` as their function values. .. note:: Similarly, you can see what happens if you uncomment ``print cheese_fnct1(cheeses)`` in the first example, say, in line 51. Another method called ``extend`` takes a list as an argument and appends all of the elements:: >>> t1=['a','b','c'] >>> t2=['d','e'] >>> t1.extend(t2) >>> print t1 ['a', 'b', 'c', 'd', 'e'] >>> print t2 ['d','e'] As shown, ``extend`` leaves ``t2`` unchanged. We saw how to use ``del(index)`` operator to remove the index-th list element:: >>> t=['a','b','c'] >>> del t[0:2] >>> print t ['c'] We can do the similar operation using ``pop``:: >>> t=['a','b','c'] >>> x=t.pop(1) >>> print t,x ['a', 'c'] b If you know the element you want to remove (but not the index), you can use ``remove``:: >>> t=['a','b','c'] >>> t.remove('b') >>> print t ['a','c']