Modifying Lists

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

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

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

images/lists/mutable_list.png

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]:

images/lists/mutable_list2.png

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 Variables and Computer Memory: Remembering Values).

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 upper, actually create new strings:

 >>>​​ ​​name​​ ​​=​​ ​​'Darwin'
 >>>​​ ​​capitalized​​ ​​=​​ ​​name.upper()
 >>>​​ ​​print(capitalized)
 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 right side of the assignment operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.241.250