Skip to main content
Engineering LibreTexts

9.1: Getting the Array Size

  • Page ID
    39390
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    To learn how long an array is (i.e., how many elements) we use the len() function, kind of like we did for strings. Refer back to Figure 8.2.3 and consider this code:

    Code \(\PageIndex{1}\) (Python):

    num_players = len(roster)

    sam_len = len(roster[2])

    big_number = len(photo_likes)

    print("There are {} players on the USWNT.".format(num_players))

    print("Sam Mewis has {} characters in her name.".format(sam_len))

    print(big_number)

    print("We've had {} elections.".format(len(prez_elections)))

    There are 24 players on the USWNT.

    Sam Mewis has 9 characters in her name.

    40000000000

    We've had 59 elections.

    This is an example of Python overloading function names, which just means that the same name is used for two different functions. When you pass a string to len(), you get the number of characters; but when you pass an array to len(), you get the number of elements it has. (The roster array had way more than 24 letters in it, notice – but len() returned 24 since that was the number of strings.)


    This page titled 9.1: Getting the Array Size is shared under a CC BY-SA 4.0 license and was authored, remixed, and/or curated by Stephen Davies (allthemath.org) via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.