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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
/lectureNote/chapters/chapt03/codes/examples/lists/cheese.py

"""

# in-operator:
cheeses = ['cheddar', 'brie','gouda']

print 'edam' in cheeses
print 'Brie' in cheeses
print 'chedda' in cheeses

# traversal
for cheese in cheeses:
    print cheese
    
# traversal on an empty list never is executed
cheeses = []
for cheese in cheeses:
    print 'this never can happen'

def cheese_fnct1(s):
    # sort() modifies the list in-place, whereas
    # sorted() builds a new sorted list from an iterable without changing the list.

    # Note: sort() is one of the methods defined in Python's list object, which means
    #       that you need to do help(list) to see the help page of sort().
    #       On the other hand, sorted() is a Python's build-in function, so that you can
    #       directly do help(sorted) to see its help page.
    
    print ''
    s_orig= list(s) #what happens if we do s_orig = s ?
    print '(1) array.sort() modifies the original array:'
    print 'input =                     ', s_orig
    s.sort()
    print 'input after input.sort() =  ', s

    print ''
    print '(2) sorted(array) does not modify the original array:'
    s=s_orig
    print 'sorted(input)=              ', sorted(s)
    print 'input =                     ',s

    print ''
    print '(3) sorted(array,reverse=True) reverses the array:'
    print 'sorted(input,reverse=True)= ', sorted(s,reverse=True)
    print 'input=                      ',s


cheeses = ['cheddar', 'brie','gouda']
print cheese_fnct1(cheeses)

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']