Builtin Functions on Lists

Section 2.6, Function Basics, on page 30 introduced a few of Python's built-in functions. Some of these, such as len, can be applied to lists as well, as can others that we haven't seen before (see Figure 5.5). Here they are in action working on a list of the half-lives3 of our plutonium isotopes:

Download lists/plu4.cmd

>>> half_lives = [87.74, 24110.0, 6537.0, 14.4, 376000.0] >>> len(half_lives) 5

>>> sum(half_lives) 406749.14000000001

We can use the results of the built-in functions in expressions; for example, the following code demonstrates that we can check whether an index is in range:

Download lists/plu5.cmd

>>> half_lives = [87.74, 24110.0, 6537.0, 14.4, 376000.0]

3. The half-life of a radioactive substance is the time taken for half of it to decay. After twice this time has gone by, three quarters of the material will have decayed; after three times, seven eighths, and so on.

0 12 3

Figure 5.6: List concatenation

Traceback (most recent call last):

File "<stdin>", line 1, in ? IndexError: list index out of range

Like all other objects, lists have a particular type, and Python complains if you try to combine types in inappropriate ways. Here's what happens if you try to "add" a list and a string:

Download lists/add_list_str.cmd

>>> [ 'H' , 'He' , 'Li'] + 'Be' Traceback (most recent call last):

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

That error report is interesting. it hints that we might be able to concatenate lists with lists to create new lists, just as we concatenated strings to create new strings. A little experimentation shows that this does in fact work:

Download lists/concat_lists.cmd

>>> original = ['H', 'He', 'Li'] >>> final = original + ['Be'] >>> final

As shown in Figure 5.6, this doesn't modify either of the original lists. instead, it creates a new list whose entries refer to the entries of the original lists.

So if + works on lists, will sum work on lists of strings? After all, if sum([1, 2, 3]) is the same as 1+2 + 3, shouldn't sum('a', 'b', 'c') be the same as 'a' + 'b' + 'c', or 'abc'? The following code shows that the analogy can't be pushed that far:

Download lists/sum_of_str.cmd

>>> sum([ 'a', 'b', 'c']) Traceback (most recent call last):

File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'

On the other hand, you can multiply a list by an integer to get a new list containing the elements from the original list repeated a certain number of times:

Download lists/mult_lists.cmd

>>> metals = 'Fe Ni'.splitO >>> metals * 3

As with concatenation, the original list isn't modified; instead, a new list is created. Notice, by the way, how we use string.split to turn the string 'Fe Ni' into a two-element list ['Fe', 'Ni']. This is a common trick in Python programs.

Was this article helpful?

0 0

Post a comment