Thursday, May 12, 2022

Mutability

As mentioned several times, one of the special things about lists is that they are mutable; that is, they can be modified in place without creating a new object. The big concern with this is remembering that, if you do this, it can affect other references to it. However, this isn't usually a large problem; it's more of something to keep in mind if you get program errors.

The following screenshot is an example of changing a list using index offset, slicing, and deleting elements:


Line 12 changes the value for the element at index 1 (second position in the list). Line 14 swaps out the first two elements for new values. Line 16 deletes the first element; removing multiple elements through slicing is also allowed.

Next to lists, dictionaries are one of the most useful data types in Python, this we'll cover in coming posts.

Share:

0 comments:

Post a Comment