9.4. List Methods¶
As with strings, Python provides us with useful methods for lists. These methods will either change an existing list, return information about the list, or create and return a new list.
9.4.1. Common List Methods¶
Here is a sample of the most frequently used list methods. More complete lists can be found here:
To see detailed examples for a particular method, click on its name.
Method |
Syntax |
Description |
---|---|---|
|
Returns the number of elements in the list that match |
|
|
Returns the index of the FIRST occurrence of |
Method |
Syntax |
Description |
---|---|---|
|
Reverses the order of the elements in a list. |
|
|
Arranges the elements of a list into increasing or decreasing order. |
Method |
Syntax |
Description |
---|---|---|
|
Adds |
|
|
Removes all elements from a list. |
|
|
Adds |
|
|
Removes and returns the element at the given |
|
|
Removes the FIRST element in a list that matches |
Method |
Syntax |
Description |
---|---|---|
|
Combines all the elements of a list into a string. |
|
|
Divides a string into smaller pieces, which are stored as separate elements in a new list. |
|
|
This is a function rather than a method, and it behaves similarly to
data conversion functions like |
9.4.2. Check Your Understanding¶
As you answer these questions, follow the links in the table above as needed.
Question
What is printed by the following code?
1 2 3 | string_list = ['coder', 'Tech', '47', '23', '350']
string_list.sort()
print(string_list)
|
[‘350’, ‘23’, ‘47’, ‘Tech’, ‘coder’]
[‘coder’, ‘Tech’, ‘23’, ‘47’, ‘350’]
[‘23’, ‘47’, ‘350’, ‘coder’, ‘Tech’]
[‘23’, ‘350’, ‘47’, ‘Tech’, ‘coder’]
Question
Which statement converts the string text = 'Coding students rock!'
into
the list ['Coding', 'students', 'rock!']
?
text.join()
text.split()
text.join("")
text.split("")
list(text)
Question
What is printed by the following program?
1 2 3 4 5 6 | grocery_bag = ['bananas', 'apples', 'edamame', 'chips', 'cucumbers', 'milk', 'cheese']
selected_items = []
selected_items = grocery_bag[2:5]
selected_items.sort()
print(selected_items)
|
[‘chips’, ‘cucumbers’, ‘edamame’]
[‘chips’, ‘cucumbers’, ‘edamame’, ‘milk’]
[‘apples’, ‘chips’, ‘edamame’]
[‘apples’, ‘chips’, ‘cucumbers’, ‘edamame’]
Question
What is printed by the following program?
1 2 3 4 | a_list = [4, 2, 8, 6, 5]
a_list.append(True)
a_list.append(False)
print(a_list)
|
[4, 2, 8, 6, 5, False, True]
[4, 2, 8, 6, 5, True, False]
[True, False, 4, 2, 8, 6, 5]
Question
What is printed by the following program?
1 2 3 4 | a_list = [4, 2, 8, 6, 5]
a_list.insert(2, True)
a_list.insert(0, False)
print(a_list)
|
[False, 4, 2, True, 8, 6, 5]
[4, False, True, 2, 8, 6, 5]
[False, 2, True, 6, 5]
Question
What is printed by the following program?
1 2 3 4 | a_list = [4, 2, 8, 6, 5]
a_list.pop(2)
a_list.pop()
print(a_list)
|
[4, 8, 6]
[2, 6, 5]
[4, 2, 6]