Skip to main content
Contents Index
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\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 4.3 List Length
As with strings, the function
len returns the length of a list (the number of items in the list). However, since lists can have items which are themselves lists, it important to note that
len only returns the top-most length. In other words, sublists are considered to be a single item when counting the length of the list.
Checkpoint 4.3.1 .
What is printed by the following statements?
alist = [3, 67, "cat", 3.14, False]
print(len(alist))
4
len returns the actual number of items in the list, not the maximum index value.
5
Yes, there are 5 items in this list.
Checkpoint 4.3.2 .
What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(len(alist))
7
Yes, there are 7 items in this list even though two of them happen to also be lists.
8
len returns the number of top level items in the list. It does not count items in sublists.
You have attempted
of
activities on this page.