Lists are objects and thus have methods. Table 6, , gives some of the most commonly used list methods.
| Method | Description |
|---|---|
L.append | Appends value v to list L |
L.clear | Removes all items from list L |
L.count | Returns the number of occurrences of v in list L |
L.extend | Appends the items in v to L |
L.index | Returns the index of the first occurrence of v in the sublist L[start:stop]. An error is reported if v doesn’t occur in the sublist. |
L.insert | Inserts value v at index i in list L, shifting subsequent items to make room |
L.pop | Removes and returns the last item of L (which must be nonempty) |
L.remove | Removes the first occurrence of value v from list L |
L.reverse | Reverses the order of the values in list L |
L.sort | Sorts the values in list L in ascending order (numerical for numbers, alphabetical for strings). The reverse flag can be set to sort in descending order. |
Here is a sample interaction that demonstrates how you can use list methods to create a list of various colors:
| | >>> colors = ['red', 'orange', 'green'] |
| | >>> colors.extend(['black', 'blue']) |
| | >>> colors |
| | ['red', 'orange', 'green', 'black', 'blue'] |
| | >>> colors.append('purple') |
| | >>> colors |
| | ['red', 'orange', 'green', 'black', 'blue', 'purple'] |
| | >>> colors.insert(2, 'yellow') |
| | >>> colors |
| | ['red', 'orange', 'yellow', 'green', 'black', 'blue', 'purple'] |
| | >>> colors.remove('black') |
| | >>> colors |
| | ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] |
All the methods shown here modify the list instead of creating a new list. The same is true for the methods clear, reverse, sort, and pop. Of those methods, only pop returns a value other than None: specifically, the item that was removed from the list. The only method that returns a list is copy, which is equivalent to L[:].
Finally, a call to append isn’t the same as using the plus sign (+). First, append appends a single value, while + expects two lists as operands. Second, append modifies the list rather than creating a new one.