The dot operator can also be used to access built-in methods of list objects. As you remember, unlike strings, lists are mutable. As a consequence, list methods can have different behaviors than string methods. Let’s look at these.
Return Type Methods: These methods work the same way as string methods: they give us a value but keep the original list the same.
Mutating Methods: These methods modify the list but do not return anything. Because of this, we shouldn’t use these methods on the right hand side of assignment (we shouldn’t assign them to a variable).
Hybrid Methods: These methods behave as both mutating and return type methods. They change the list and also return a value.
The following table provides a summary of the list methods shown above. The column labeled behavior gives an explanation as to what the return value is as it relates to the new value of the list.
Table4.10.1.
Method
Parameters
Behavior
Description
append
item
mutating
Adds a new item to the end of a list
insert
position, item
mutating
Inserts a new item at the position given
pop
none
hybrid
Removes and returns the last item
pop
position
hybrid
Removes and returns the item at position
sort
none
mutating
Modifies a list to be sorted
reverse
none
mutating
Modifies a list to be in reverse order
index
item
return idx
Returns the position of first occurrence of item, error if not found
count
item
return ct
Returns the number of occurrences of item
remove
item
mutating
Removes the first occurrence of item
Here are some examples on these methods. Be sure to experiment with them to gain a better understanding of what they do. You are expected to be comfortable using these methods!
Another way to add items:
Some return type methods:
Some mutating methods:
It is important to remember that methods like append, sort, and reverse all return None. This means that re-assigning mylist to the result of sorting mylist will result in losing the entire list.
Some hybrid methods:
Notice that there are two ways to use the pop method. The first, with no parameter, will remove and return the last item of the list. If you provide a parameter for the position, pop will remove and return the item at that position. Either way the list is changed. Hybrid methods will also change the list without assignment to a variable, as shown with the last example above.