- The "append()" method takes a data item and adds it to the end of the list. Opposed to this is the "pop()" method, which returns the last item of the list. However, joined with the pop method a list can then become a representation of a stack data structure (in which all new data goes "on top" of the stack and return values are the last item on the stack, following a "last in, first out pattern). For example:
>>>ex_list = ['a', 'b', 'c']
>>>ex_list.append('d')
>>>print ex_list
['a' 'b' 'c' 'd']
>>>x = ex_list.pop()
>>>print x
'd' - Using the "insert()" and "remove()" methods programmers can place items within the list at a specific given point or remove an item based on its value. Both of these methods work throughout the list rather than at just the end of it. For example,
>>>ex_list.insert(2, 'f')
>>>print ex_list
['a', 'b', 'f', 'c']
>>>ex_list.remove('f')
>>>print ex_list
['a', 'b', 'c']
The remove method will only remove the first instance of item to remove. If there are multiple instances, the other remaining values will need to be removed as well (if desired). - The "sort()" method does just as its name implies: it sorts the list in ascending order. This applies to lists of words, numbers or characters. The "reverse()" method also performs a function suitable for its name: it reverses the list's current order with the last element first, and the first last. For example:
>>>ex_list.reverse()
>>>print ex_list
['c', 'b', 'a']
>>>ex_list.sort()
>>>print ex_list
['a', 'b', 'c'] - Programmers can also take out parts of a list (or "slice" the list) using list notation. Typically, a programmer references an item in a list by its index. For example, the value 'b' in ex_list could be taken from "ex_list[1]". However, larger sublists of a list can also be removed by slicing out smaller parts of the list:
>>>print ex_list[0:2]
['a', 'b']
>>>print ex_list[1:]
['b', 'c']
>>>print ex_list[:2]
['a', 'b']
previous post
next post