Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Collections

Computer science has built a whole discipline around studying collections and their various behaviours. Sometimes collections are called containers. In this section we will look first of all at the collections supported in Python then we’ll conclude with a brief summary of some other collection types you might come across in other languages.

Python Collections

List

A list is a sequence of items. What makes it different from an array is that it can keep on growing - you just add another item. But it's not usually indexed so you have to find the item you need by stepping through the list from front to back checking each item to see if it's the item you want. Both Python and Tcl have lists built into the language. In BASIC it's harder and we have to do some tricky programming to simulate them. BASIC programmers usually just create very big arrays instead. Python also allows you to index it's lists. As we will see this is a very useful feature.

List operations

Python provides many operations on collections. Nearly all of them apply to Lists and a subset apply to other collection types, including strings which are just a special type of list of characters. To create and access a list in Python we use square brackets. You can create an empty list by using a pair of square brackets with nothing inside, or create a list with contents by separating the values with commas inside the brackets:

>>>aList = []

>>>another = [1,2,3]

>>>print another [1, 2, 3]

We can access the individual elements using an index number, where the first element is 0, inside square brackets:

>>> print another[2] 3

We can also change the values of the elements of a list in a similar fashion:

>>>another[2] = 7

>>>print another [1, 2, 7]

You can use negative index numbers to access members from the end of the list. This is most commonly done using -1 to get the last item:

>>> print another[-1] 7

We can also add new elements to the end of a list using the append() operator:

>>>aList.append(42)

>>>print aList [42]

We can even hold one list inside another, thus if we append our second list to the first:

>>> aList.append(another)

26

>>> print aList [42, [1, 2, 7]]

Notice how the result is a list of two elements but the second element is itself a list (as shown by the []’s around it). This is useful since it allows us to build up representations of tables or grids using a list of lists. We can then access the element 7 by using a double index:

>>> print aList[1][2] 7

The first index, 1, extracts the second element which is in turn a list. The second index, 2, extracts the third element of the sublist.

The opposite of adding elements is, of course, removing them and to do that we use the del command:

>>>del aList[1]

>>>print aList [42]

If we want to join two lists together to make one we can use the same concatenation operator ‘+’ that we saw for strings:

>>>newList = aList + another

>>>print newList

[42, 1, 2, 7]

In the same way we can apply the repetition operator to populate a list with multiples of the same value:

>>>zeroList = [0] * 5

>>>print zeroList [0, 0, 0, 0, 0]

Finally, we can determine the length of a list using the built-in len() function:

>>>print len(aList)

2

>>>print len(zeroList)

5

Tcl Lists

Tcl also has a built in list type and a variety of commands for operating on these lists. These commands are identifiable by the 'l' prefix, for example linsert,lappend, lindex, etc. An example of creating a simple Tcl list and accessing a member follows:

%set L [list 1 2 3]

%put [lindex $L 2]

3

27

Tuple

Not every language provides a tuple construct but in those that do it’s extremely useful. A tuple is really just an arbitrary collection of values which can be treated as a unit. In many ways a tuple is like a list, but with the significant difference that tuples are immutable which is to say that you can’t change them nor append to them once created. In Python, tuples are simply represented by parentheses containing a comma separated list of values, like so:

>>> aTuple = (1,3,5)

>>> print aTuple[1] # use indexing like a list 3

>> aTuple[2] = 7 # error, can’t change a tuple’s elements Traceback (innermost last):

File "", line 1, in ? aTuple[2] = 7

TypeError: object doesn't support item assignment

The main things to remember are that while parentheses are used to define the tuple, square brackets are used to index it and you can’t change a tuple once its created. Otherwise most of the list operations also apply to tuples.

Dictionary or Hash

A dictionary as the name suggests contains a value associated with some key, in the same way that a literal dictionary associates a meaning with a word. The value can be retrieved by ‘indexing’ the dictionary with the key. Unlike a literal dictionary the key doesn’t need to be a character string(although it often is) but can be any immutable type including numbers and tuples. Similarly the values associated with the keys can be any kind of Python data type. Dictionaries are usually implemented internally using an advanced programming technique known as a hash table. For that reason a dictionary may sometimes be referred to as a hash. This has nothing to do with drugs!

Because access to the dictionary values is via the key you can only put in elements with unique keys. Dictionaries are immensely useful structures and are provided as a built-in type in Python although in many other languages you need to use a module or even build your own. We can use dictionaries in lots of ways and we'll see plenty examples later, but for now, here's how to create a dictionary in Python, fill it with some entries and read them back:

>>>dict = {}

>>>dict['boolean'] = "A value which is either true or false"

>>>dict['integer'] = "A whole number"

>>>print dict['boolean']

A value which is either true or false

Notice that we initialise the dictionary with braces, then use square brackets to assign and read the values.

Due to their internal structure dictionaries do not support very many of the collection operators that we’ve seen so far. None of the concatenation, repetition or appending operations work. To assist us in accessing the dictionary keys there is a function that we can use, keys(), which returns a list of all the keys in a dictionary.

If you're getting a bit fed up, you can jump to the next chapter at this point. Remember to come back and finish this one when you start to come across types of data we haven't mentioned so far.

28