Section 9.6 List methods
Python provides methods that operate on lists. For example, append
adds a new element to the end of a list:
Checkpoint 9.6.1.
alist = [4, 2, 8, 6, 5]
alist.append(True)
alist.append(False)
print(alist)
[4, 2, 8, 6, 5, False, True]
True was added first, then False was added last.
[4, 2, 8, 6, 5, True, False]
Yes, each item is added to the end of the list.
[True, False, 4, 2, 8, 6, 5]
append adds at the end, not the beginning.
extend
takes a list as an argument and appends all of the elements:
This example leaves t2
unmodified.
sort
arranges the elements of the list from low to high:
Checkpoint 9.6.2.
Q-5: True or False? The sort method alphabetizes lists.
True
While this may be true if the values are letter characters, sort can be used on lists with different elements, too.
False
The sort method puts elements in order of low to high, this can be true for letters, numbers, or whatever the elements of the list are.
Most list methods are void; they modify the list and return None
. If you accidentally write t = t.sort()
, you will be disappointed with the result.
Checkpoint 9.6.3.