In this lesson, we learned about a few more functions pertaining to lists within Python. The .append() method allows you to add a further item to the end of your existing list, so this is how you add 'teach Python' to myGoals:
The .insert() method is similar to the "append" function, however "insert" requires that you designate a place that your new item should be inserted. This is done by typing the insert command in much the same way as the append command above, but also placing the target index BEFORE the string or item you wish to insert. For example, myGoals.insert(3,'brush teeth daily') will insert 'brush teeth daily' into the fourth spot on your list (remember again that indexing starts with 0 in Python):
Predictably, the .remove() method allows you to remove an item from your list. It is typed listName.remove('item') in the same manner as the insert and append functions:
You do not have to specify the placing of the item you wish to remove, however, understandably, Python cannot remove items that are not on the given list, and will return an error when told to do so.
Learn More
Note that .remove() removes only the first instance even when duplicates exist. Below, only the first 'b' is removed.
It is also possible to delete an item based on its position. .pop() is the method to use. If the position is not specified, it removes the very last item. Otherwise it removes the item at the designated position and shifts up the remaining items. In either case, the removed item is returned. (.pop() is the only list method that modifies a list in place AND returns a value. See Mutability for the distinction.)
>>> li = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> li.pop()
'g'>>> li
['a', 'b', 'c', 'd', 'e', 'f']>>> li.pop(2)
'c'>>> li
['a', 'b', 'd', 'e', 'f']
.extend() is another list method that's handy. It is used to extend a list by another list. Below, the list [1,2,3,4,5] is extended by three new items:
>>> li = [1,2,3,4,5]
>>> li.extend([6,7,8])
>>> li
[1, 2, 3, 4, 5, 6, 7, 8]
You must, however, take care NOT TO CONFUSE .extend() and .append(). Try li.append([6,7,8]) in the example above and see what happens. If you want to torture yourself further, try li.append('hello') and li.extend('hello'). (Hint: In the latter, Python is forced to interpret 'hello' as a list.)
Practice
Here is a very incomplete list of planets: planets = ['venus', 'mercury', 'earth', 'mars', 'jupiter']. Using list methods, turn it into a complete and correctly ordered list. You can choose whether or not to include "pluto".