Modifying Lists

Suppose we're typing in a list of the noble gases2 and our fingers slip:

Download lists/noblesl.cmd

>>> nobles = ['helium' , 'none', 'argon', 'krypton' , 'xenon', 'radon']

The error here is that we typed 'none' instead of 'neon'. Rather than retyping the whole list, we can assign a new value to a specific element of the list:

Download lists/nobles2.cmd

>>> nobles = ['helium' , 'none', 'argon', 'krypton' , 'xenon', 'radon'] >>> nobles[1] = 'neon' >>> nobles

['helium' , 'neon', 'argon', 'krypton' , 'xenon', 'radon']

2. A noble gas is one whose outermost electron shell is completely full, which makes it chemically inert.

Before

After

After

Figure 5.4: List mutation

In Figure 5.4, we show what the assignment to nobles[1] did. It also shows that lists are mutable, in other words, that their contents can be changed after they have been created. In contrast, numbers and strings are immutable. You cannot, for example, change a letter in a string after you have created it. Methods that appear to, like upper, actually create new strings:

Download lists/strings_immutable.cmd

>>> name = 'Darwin' >>> capitalized = name.upperO >>> print capitalized 'DARWIN' >>> print name 'Darwin'

The expression L[i] behaves just like a simple variable (see Section 2.4, Variables and the Assignment Statement, on page 25). If it's on the right, it means "Get the value of the item at location i in the list L." If it's on the left, it means "Figure out where item i in the list L is located so that we can overwrite it."

Figure 5.5: List functions

Description

Returns the number of items in list L Returns the maximum value in list L Returns the minimum value in list L Returns the sum of the values in list L

Was this article helpful?

0 0

Post a comment