Книга: Practical Programming, Fourth Edition
Назад: Type Annotations for Lists
Дальше: Operations on Lists

Modifying Lists

Suppose you’re typing in a list of the noble gases and your fingers slip:

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

Lists are mutable

The error here is that you typed ’none’ instead of ’neon’. Here’s the memory model that was created by that assignment statement:

Mutable list

Rather than retyping the whole list, you can assign a new value to a specific element of the list:

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

Here is the result after the assignment to nobles[1]:

Mulatble list

That memory model also shows that list objects are mutable. That is, the contents of a list can be mutated.

In the previous code, nobles[1] was used on the left side of the assignment operator. It can also be used on the right side. In general, an expression of the form L[i] (list L at index i) behaves just like a simple variable (see ).

If L[i] is used in an expression (such as on the right of an assignment statement), it means “Get the value referred to by the memory address at index i of list L.”

On the other hand, if L[i] is on the left of an assignment statement (as in nobles[1] = ’neon’), it means “Look up the memory address at index i of list L so it can be overwritten.”

In contrast to lists, numbers and strings are immutable. You cannot, for example, change a letter in a string. Methods that appear to do that, like str.upper, actually create new strings:

 >>>​​ ​​name​​ ​​=​​ ​​'Darwin'
 >>>​​ ​​print(name.upper())
 DARWIN
 >>>​​ ​​print(name)
 Darwin

Because strings are immutable, it is only possible to use an expression of the form s[i] (string s at index i) on the RHS.

Назад: Type Annotations for Lists
Дальше: Operations on Lists