9.6. List methodsΒΆ
Python provides methods that operate on lists. For example,
append
adds a new element to the end of a list:
- [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.
Q-2: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
alist.append(True)
alist.append(False)
print(alist)
Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
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:
- 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.
Q-5: True or False? The sort method alphabetizes lists.
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.