List object methods
Python includes several handy methods that are available to all lists.
For example, use append() and extend() to add to the end of a list. These methods work on lists much like an augmentation ("+=") operator works on other variables.
groupMembers = ['Jordan', 'Parker']
groupMembers.append('Quinn')
groupMembers
The output is:
['Jordan', 'Parker', 'Quinn']
Notice that you passed an item, not a list, to append(). Passing a list to append() gives you this result:
groupMembers2 = ['Jordan', 'Parker', 'Quinn']
groupMembers2.append(['Stuart', 'Pete'])
groupMembers2
The output is:
['Jordan', 'Parker', 'Quinn', ['Stuart', 'Pete']]
To tack items from a new list onto the end of an existing list, use extend() instead:
groupMembers.extend(['Stuart', 'Pete'])
groupMembers
The output is:
['Jordan', 'Parker', 'Quinn', 'Stuart', 'Pete']
The index() method returns the index of the first matching item in a list (if the item is present):
groupMembers.index('Quinn')
The output is:
2
The count() method returns the number of items in a list that match objects that you pass in:
groupMembers.count('Jordan')
The output is:
1
There are two methods for removing items from a list. The first is remove(), which locates the first occurrence of an item in the list and removes it (if the item is present):
groupMembers.remove('Stuart')
groupMembers
The output is:
['Jordan', 'Parker', 'Quinn', 'Pete']
The other method for removing items from a list is the pop() method. If you supply pop() with an index number, it removes the item from that location in the list and returns it. If you specify no index, pop() removes the last item from the list and returns that:
groupMembers.pop()
The output is:
'Pete'
The insert() method adds an item to a specific location in a list:
groupMembers.insert(1, 'Riley')
groupMembers
The output is:
['Jordan', 'Riley', 'Parker', 'Quinn']
Unsurprisingly, the reverse() method reverses the order of the items in a list:
groupMembers.reverse()
groupMembers
The output is:
['Quinn', 'Parker', 'Riley', 'Jordan']
Finally, the sort() method orders the items in a list:
groupMembers.sort()
groupMembers
The output is:
['Jordan', 'Parker', 'Quinn', 'Riley']
Try it yourself
- What happens if you run
groupMembers.extend(groupMembers)? - How about
groupMembers.append(groupMembers)?
Hint (expand to reveal)
Here's the input:
groupMembers.extend(groupMembers)
groupMembers
The output is:
['Quinn', 'Jordan', 'Parker', 'Riley', 'Quinn', 'Jordan', 'Parker', 'Riley']
The next input is:
groupMembers.append(groupMembers)
groupMembers
Here's the output:
['Quinn', 'Jordan', 'Parker', 'Riley', ['Quinn', 'Jordan', 'Parker', 'Riley']]
Note
You can supply your own lambda function for the sort() method, for use in comparing items in a list. We cover lambda functions in a later unit.