Exercise 1.5

Objectives:

  • How to create and manipulate lists/arrays of values.

  • Continued use of Python’s interactive mode as a tool for experimentation.

Files Created: None

In this exercise, we experiment with Python’s list datatype. In the last exericse, you worked with strings containing stock symbols. For example:

>>> symbols = 'HPQ,AAPL,IBM,MSFT,YHOO,DOA,GOOG'
>>>

Define the above variable and split it into a list of names using the split() operation of strings:

>>> symlist = symbols.split(',')
>>> symlist
['HPQ', 'AAPL', 'IBM', 'MSFT', 'YHOO', 'DOA', 'GOOG']
>>>

(a) Extracting and reassigning list elements

Lists work like arrays where you can look up and modify elements by numerical index. Try a few lookups:

>>> symlist[0]
'HPQ'
>>> symlist[1]
'AAPL'
>>> symlist[-1]
'GOOG'
>>> symlist[-2]
'DOA'
>>>

Try reassigning one of the items:

>>> symlist[2] = 'AIG'
>>> symlist
['HPQ', 'AAPL', 'AIG', 'MSFT', 'YHOO', 'DOA', 'GOOG']
>>>

Take a few slices:

>>> symlist[0:3]
['HPQ', 'AAPL', 'AIG']
>>> symlist[-2:]
['DOA', 'GOOG']
>>>

If you want to make a new list from scratch with the intent of appending items to it, you simply do this:

>>> mysyms = []
>>> mysyms.append('GOOG')
>>> mysyms
['GOOG']
>>>

You can reassign a portion of a list to another list. For example:

>>> symlist[-2:] = mysyms
>>> symlist
['HPQ', 'AAPL', 'AIG', 'MSFT', 'YHOO', 'GOOG']
>>>

When you do this, the list on the left-hand-side will be resized as appropriate to make the right-hand-side fit. For instance, in the above example, the last two items of symlist got replaced by the single item in the list mysyms.

(b) Looping over list items

The for loop works by looping over data in a sequence such as a list. Check this out by typing the following loop and watching what happens:

>>> for s in symlist:
        print 's =', s

... look at the output ...

(c) Membership tests

Use the in or not in operator to check if 'AIG','AA', and 'CAT' are in the list of symbols.

>>> 'AIG' in symlist
True
>>> 'AA' in symlist
False
>>> 'CAT' not in symlist
True
>>>

(d) Appending, inserting, and deleting items

Use the append() method to add the symbol 'RHT' to end of symlist.

>>> symlist.append('RHT')
>>> symlist
['HPQ', 'AAPL', 'AIG', 'MSFT', 'YHOO', 'GOOG', 'RHT']
>>>

Use the insert() method to insert the symbol 'AA' as the second item in the list.

>>> symlist.insert(1,'AA')
>>> symlist
['HPQ', 'AA', 'AAPL', 'AIG', 'MSFT', 'YHOO', 'GOOG', 'RHT']
>>>

Use the remove() method to remove 'MSFT' from the list.

>>> symlist.remove('MSFT')
>>> symlist
['HPQ', 'AA', 'AAPL', 'AIG', 'YHOO', 'GOOG', 'RHT']
>>>

Append a duplicate entry for 'YHOO' at the end of the list. Note: it is perfectly fine for a list to have duplicate values.

>>> symlist.append('YHOO')
>>> symlist
['HPQ', 'AA', 'AAPL', 'AIG', 'YHOO', 'GOOG', 'RHT', 'YHOO']
>>>

Use the index() method to find the first position of 'YHOO' in the list.

>>> symlist.index('YHOO')
4
>>> symlist[4]
'YHOO'
>>>

Count how many times 'YHOO' is in the list:

>>> symlist.count('YHOO')
2
>>>

Remove the first occurrence of 'YHOO'.

>>> symlist.remove('YHOO')
>>> symlist
['HPQ', 'AA', 'AAPL', 'AIG', 'GOOG', 'RHT', 'YHOO']
>>>

Just so you know, there is no method to find or remove all occurrences of an item. However, we’ll see an elegant way to do this in section 2.

(e) List sorting

Want to sort a list? Use the sort() method. Try it out:

>>> symlist.sort()
>>> symlist
['AA', 'AAPL', 'AIG', 'GOOG', 'HPQ', 'RHT', 'YHOO']
>>>

Want to sort in reverse? Try this:

>>> symlist.sort(reverse=True)
>>> symlist
['YHOO', 'RHT', 'HPQ', 'GOOG', 'AIG', 'AAPL', 'AA']
>>>

Note: Sorting a list modifies its contents "in-place." That is, the elements of the list are shuffled around, but no new list is created as a result.

(f) Putting it all back together

Want to take a list of strings and join them together into one string? Use the join() method of strings like this (note: this looks funny at first).

>>> a = ','.join(symlist)
>>> a
'YHOO,RHT,HPQ,GOOG,AIG,AAPL,AA'
>>> b = ':'.join(symlist)
>>> b
'YHOO:RHT:HPQ:GOOG:AIG:AAPL:AA'
>>> c = ''.join(symlist)
>>> c
'YHOORHTHPQGOOGAIGAAPLAA'
>>>

(g) Lists of anything

Lists can contain any kind of object, including other lists (e.g., nested lists). Try this out:

>>> nums = [101,102,103]
>>> items = ['spam',symlist, nums]
>>> items
['spam', ['YHOO', 'RHT', 'HPQ', 'GOOG', 'AIG', 'AAPL', 'AA'], [101, 102, 103]]
>>>

Pay close attention to the above output. items is a list with three elements. The first element is a string, but the other two elements are lists. You can access items in the nested lists by simply using multiple indexing operations. For example:

>>> items[0]
'spam'
>>> items[0][0]
's'
>>> items[1]
['YHOO', 'RHT', 'HPQ', 'GOOG', 'AIG', 'AAPL', 'AA']
>>> items[1][1]
'RHT'
>>> items[1][1][2]
'T'
>>> items[2]
[101, 102, 103]
>>> items[2][1]
102
>>>

Even though it is technically possible to make very complicated list structures, as a general rule, you want to keep things simple. Usually lists hold items that are all the same kind of value. For example, a list that consists entirely of numbers or a list of text strings. Mixing different kinds of data together in the same list is often a good way to make your head explode so it’s best avoided.

Links