## Lists

A list is a mutable sequence of objects. A list is denoted by brackets:

You can also create a list using the list() function. This is useful when converting different sequences to a list, say, from a string:

A list can be modified. You can add another element to a list by using the + operator. The + operator concatenates lists, so you have to supply another list:

»> [1, 'hey', l+2j] + ['hey', 'hey'] [1, 'hey', (l+2j), 'hey', 'hey']

The following, however, will fail, since you cannot add an integer to a list:

Traceback (most recent call last):

File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "int") to list

The proper way to do this would be to form another list, made solely of the value 2:

If you're looking to add the value 2 to each and every element of the list [l, 2, 3], that is, to modify the list to [3, 4, 5], you'll get the details in the sections "The for Statement" and "List Comprehensions" later in this chapter.

A list is an object too, so you can also have a list inside a list:

Now things get trickier, both in describing the object and in actually performing operations. Say you'd like to add another list, [5, 6], to the preceding example. How exactly would you like to add it? Should the updated list be [[l, 2], [3, 4], [5, 6]] or [[l, 2], [3, 4], 5, 6] or [[[1, 2], [3, 4]], [5, 6]] (which really is shamelessly tricky)?

The way I like to describe the data structure [[l, 2], [3, 4]] is as a list of rows. The first row is [l, 2] and the second row is [3, 4].

Here are some of the things you can do to concatenate lists:

»> [[1, 2], [3, 4]] + [5, 6] [[1, 2], [3, 4], 5, 6]

»> [[1, 2], [3, 4]] + [[5, 6]] [[1, 2], [3, 4], [5, 6]]

The first line adds the elements 5 and 6. The second line adds the row [5, 6]. Another option is to use a variable to hold the list, L, and use the append() and extendQ methods:

»> L = [[1, 2], [3, 4]] >>> L.append([5, 6])

The method append() adds an item to the list, in this case the list [5, 6]. The method extend() adds elements from the sequence one by one to the list, in this case, the elements 7 and 8. It's a bit hard to follow at first, but experiment with lists interactively to get a feel for how to use them properly.

Lists can also be indexed, similarly to strings:

The last statement, L[l][l], requires some explanation. The statement L[l] returns the second element in the list (indices start at 0, so index 1 is the second element). For our purposes, let's mentally assign L[l] to variable M. But variable M is a list as well: [2, 3, 4]. So clearly we can index M as well: M[l] is 3. Instead of doing those two steps, we can write this more compactly as L[l][l].

Lists much like strings can also be sliced:

»> L = [['hey', '1'], [2, 3, 4], "] »> L[:-l]

You can check whether an item is in a list using the in operator:

>>> 'hey' in ['hey', 'hey', 'split', 'second'] True

You can count the number of elements in a list using the len() statement:

Since lists are mutable, they can be reassigned:

»> L = [['hey', '1'], [2, 3, 4], "] >>> L[l] = [4, 5, 6]

or have items removed using the del statement:

»> L = [['hey', '1'], [2, 3, 4], "] »> del L[0]

Lists also have methods, functions that operate only on list objects such as append() and extend(), shown previously. To use a method, follow the list object with a dot and the function name with parentheses and parameters within (empty ones in case of no parameters):

>>> L = ['hey', 'hey', 'split', 'second'] >>> L.count('hey') 2

I've used the methods count(), which counts the occurrences of an item in a list, and sort(), which sorts a list. Table 3-3 describes the list methods along with some examples. In the examples, assume that L is ['second', 'second', 8].

Table 3-3. List Methods

Method

Description

Example append(obj)

count(val) extend(iterable)

insert(n, obj)

Adds an element to the end of a list.

Returns the number of times val appears in the list.

Adds elements to the list from iterable (more on iterators and iterables later in this chapter).

Returns the first index of val in the list. If start is supplied, this method returns the first index that is greater than start; if stop is supplied, the index also has to be less than stop.

Inserts an object at index n.

L.append('hey') changes L to ['second', 'second', 8, 'hey'].

L.count('second')returns 2.

L.extend(xrange(2)) changes L to ['second', 'second', 8, 0, 1].

L.index('second')returns 0. L.index('second', l) returns 1. L.index('second', 2, 3) raises an exception x not in list.

L.insert(2, 'me') changes L to ['second', 'second', 'me', 8].

Continued

 Method Description Example pop([n]) Returns the nth element in the list and removes it. If n is not supplied, this method returns the last element. L.pop() returns 8, and the modified list is ['second', 'second']. L.pop(-3)returns 'second', and the modified list is ['second', L.remove('second') changes L to ['second', 8]. remove(val) Removes the first occurrence of val in x. reverseQ Reverses the list. L.reverseQ modifies L to [8, 'second', 'second']. sort() Sorts the list. You can supply a sort function to the list; see help(list.sort). L.sortQ modifies L to [8, 'second', 'second'].

Was this article helpful?

0 0