Skip to main content\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 9.7 Deleting elements
There are several ways to delete elements from a list. If you know the index of the element you want, you can use
pop:
pop modifies the list and returns the element that was removed. If you donβt provide an index, it deletes and returns the last element.
Activity 9.7.1.
What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
temp = alist.pop(2)
temp = alist.pop()
print(alist)
-
[4, 8, 6]
-
pop(2) removes the item at index 2, not the 2 itself.
-
[2, 6, 5]
-
pop() removes the last item, not the first.
-
[4, 2, 6]
-
Yes, first the 8 was removed, then the last item, which was 5.
Activity 9.7.2.
What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
alist = alist.pop(0)
print(alist)
-
[2, 8, 6, 5]
-
alist is now the value that was returned from pop(0).
-
[4, 2, 8, 6, 5]
-
pop(0) changes the list by removing the first item.
-
4
-
Yes, first the 4 was removed from the list, then returned and assigned to alist. The list is lost.
-
None
-
pop(0) returns the first item in the list so alist has now been changed.
If you donβt need the removed value, you can use the
del operator:
If you know the element you want to remove (but not the index), you can use
remove:
The return value from
remove is
None.
To remove more than one element, you can use
del with a slice index:
As usual, the slice selects all the elements up to, but not including, the second index.
Activity 9.7.3.
What is the value of alist after the following code executes?
alist = ['a', 'b', 'c', 'd', 'e', 'f']
del alist[1:5]
print(alist)
-
[βaβ, βbβ, βcβ, βdβ, βeβ, βfβ]
-
The del method removes part of the list, so it will be shorter.
-
[βaβ, βfβ]
-
βaβ is the 0th element of the list and βfβ is the 5th element of the list, so these are the values that remain after deleting [1:5].
-
[βfβ]
-
Remember that lists start at 0, not 1, and that a slice stops before the second element - not after.
-
[βbβ, βcβ, βdβ, βeβ]
-
These are the values that will be deleted with the slice [1:5]
Activity 9.7.4.
You have attempted
of
activities on this page.