Concepts / Working with Mutable and Immutable Types

Working with Mutable and Immutable Types

A mutable object can be modified in place.

  • Programming

One Operation, Two Kinds of Change

Python operations do not all handle data in the same way. A list can be changed directly, while a string operation creates a new string. That difference matters whenever more than one variable refers to the same list or when you expect a method call to produce a value.

What do you think happens?

Suppose two variables refer to the same list. If one variable is used with append, what should the other variable show afterward?

  • The other variable still shows the old list

  • The other variable shows the modified list

  • The other variable becomes None

Reveal answer
Answer:

The other variable shows the modified list.

A list is mutable. An in-place method changes the original list object, so every variable referring to that object sees the change.

Tracking the Original Object

A mutable object can be modified in place. Lists are mutable, so methods such as append() and sort() change the original list object rather than creating a separate list that you must assign back. The variable continues to refer to that same list object, but the contents of the object have changed.

[1, 2, 3]list objecttextstring value[1, 2, 3, 4]same list objectnew textnew stringin-place list changestring operation
What changes when a list is modified in place compared with when a string operation produces a new string?
python

After the append call, both items and other_name refer to the list whose contents are [1, 2, 3, 4]. Assigning another variable to the list does not create an independent list in this situation; both variables refer to the same list object.

Methods and Their Owners

Definition

A method is a function defined specifically for a class. For a list object, its methods are accessed with dotted notation, such as mylist.append(item). A standalone function is not tied to one particular object in that way.

list objectmyliststandalone functionnot tied to one objectappendobject methodlist objectpassed as an argumentdotted notationreceives object
How does control and data flow differ between calling object.method() and calling a standalone function(object)?

The dot in mylist.append(item) connects the object to a method available through that object's class. This is why the list name appears before the dot and the method name appears after it. The source describes the corresponding standalone-function form append(mylist, item) as different from the method form because append is being accessed as part of the list object's available methods.

mylistlist objectlistobject's classappendavailable methodbelongs todefines
How does Python determine which methods are available when a method is called with dotted notation on an object?

Return Values from In-Place Methods

An in-place list method has two effects that must be kept separate. First, it changes the original list. Second, it returns None rather than returning a new list. The sort() method follows this pattern: it changes the list directly and returns None.

[1, 2, 3]original listNonemethod return valueappend(4)in-place method[1, 2, 3, 4]same list objectcall methodchanges in placereturns
What happens to the original list, and what value is returned, when an in-place method such as append is called?
Code walkthrough
numbers = [3, 1, 2]
result = numbers.sort()
  1. 1
    numbers refers to a list containing 3, 1, and 2.
  2. 2
    numbers.sort() changes that original list in place.
  3. 3
    result receives the method's return value, which is None.
Output
numbers is [1, 2, 3]
result is None

Strings Follow a Different Pattern

Strings are immutable types. In the source's comparison, operations on strings always create new string objects rather than changing the original string in place. This contrasts with list methods such as append() and sort(), which modify the list where it exists.

python

In this example, the string operation produces a new string value for new_word. The original string referred to by word is not modified in place. The important question is therefore: does the operation change the existing object, as list mutation does, or produce a new object, as string operations do?

FeatureListString
MutabilityMutableImmutable
Effect of the operation described in the sourceThe original list can be changed in placeA new string is created
Example operationappend() or sort()A string operation
Return behavior for the listed in-place methodsappend() and sort() return NoneString operations create a new string

The central difference is whether the original object can be changed directly.

Finding Methods with help

When you need to discover what operations a list supports, call help(list). The help() function displays documentation for the list class, including its available methods and descriptions of what those methods do. This is a practical way to explore list capabilities instead of trying to remember every method name.

python
help(list)documentation requestlistclass documentationlist methodsnames and descriptionsopens documentation forincludes
Where can a learner find available list methods and their descriptions when using help(list)?

Mistakes Beginners Make

  • Common mistake

    Expecting sort() to return a sorted list.

    What it looks like
    sorted_numbers = numbers.sort()
    Why it fails

    sort() changes the original list in place and returns None.

    Do this instead

    Treat the list itself as the changed result and do not expect the method call to provide a new list.

  • Common mistake

    Assuming a second variable holds an independent list.

    What it looks like
    other_name = items; items.append(4)
    Why it fails

    Multiple variables can refer to the same list object, so a change through one variable is visible through the other.

    Do this instead

    Remember that an in-place change affects all variables referring to that list.

  • Common mistake

    Treating a string operation like a list mutation.

    What it looks like

    Expecting an operation on a string to change the original string directly.

    Why it fails

    Strings are immutable, so string operations create new strings rather than modifying the original string in place.

    Do this instead

    Expect a new string value from a string operation and distinguish that behavior from list mutation.

  • Common mistake

    Calling a list method as though it were a detached operation.

    What it looks like

    Writing append(mylist, item) when the intended form is mylist.append(item).

    Why it fails

    List methods are accessed through the list object using dotted notation.

    Do this instead

    Use the object.method() pattern for methods belonging to the object's class.

Practice the Prediction

MEDIUM

For each situation, predict the state of the variables and the method return value before checking your reasoning: a list is assigned to two variables and append() is called through one of them; a list is passed to sort() and the call is assigned to another variable; a string operation is used and its result is assigned to a new variable.

Hints
  • Ask whether the object is mutable or immutable.
  • For a list method, separate the change to the list from the value returned by the method.
  • Check whether both variables refer to the same list.
  1. 1
    Identify the object receiving the dotted method call.
  2. 2
    Decide whether the object is a mutable list or an immutable string.
  3. 3
    If the object is a list, determine whether the method changes it in place.
  4. 4
    Record the method's return value separately from the object's new contents.
  5. 5
    Check whether another variable refers to the same list object.

Key Takeaways

  1. 1
    Methods belong to specific classes and are accessed through dotted notation on objects.
  2. 2
    Lists are mutable, so append() and sort() can change the original list in place.
  3. 3
    In-place list methods change the list and return None.
  4. 4
    Multiple variables can refer to the same list, so a change through one variable affects the others.
  5. 5
    Strings are immutable, so string operations create new strings instead of modifying the original string in place.
  6. 6
    help(list) displays documentation for the list class and its methods.

At a glance

  • A method is defined for a class and called through an object with dotted notation.
  • List methods such as append() and sort() modify the original list in place.
  • These in-place methods return None, so their mutation effect must be separated from their return value.
  • Strings are immutable, so string operations create new strings rather than changing the original string.
  • Use help(list) to explore list methods and their documentation.

Related concepts

More concepts starting with W