Skip to main content
Engineering LibreTexts

14.3: Iterating Through an Array

  • Page ID
    39294
  • \( \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}}\)

    Most often, we’ll use a for loop to “loop through,” or “iterate through,” the contents of an aggregate data variable. This means that instead of executing a snippet of code once, we’ll execute it once per element of the variable. This “once per element” thing is what makes the code non-linear.

    Let’s start with the first aggregate data type we learned, a NumPy array.

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

    1: villains = np.array(['Jafar','Ursula','Scar','Gaston'])

    2: print("Here we go!")

    3: for v in villains:

    4: print("Oooo, {} is scary!".format(v))

    5: print("({} has {} letters.)".format(v, len(v)))

    6: print("Whew!")

    (I’ve numbered the lines in this example so I can refer to them in the text below, but the numbers and colons aren’t part of Python.)

    Immediately after creating our villains array, and printing an introductory message, we encounter our first loop. A loop consists of two parts: the loop header and the loop body. Here are the rules:

    • The loop header consists of the line that begins with “for”.
    • The loop body consists of all of the consecutive following lines that are indented (tabbed-over) one tab.2

    That second rule turns out to be more important than it seems at first. A very (very!) common error among beginners is to “misindent” their code such that their loop body includes more, or less, than they mean it to. So heads up.

    Before we continue, stare at that code above and convince yourself of these two facts:

    • The loop header is line 3
    • The loop body is lines 4 and 5. (Not line 4 only! Not lines 4, 5, and 6!)

    Now the reason this is important is that a for loop works as follows:

    1. First, create a new variable (on the left-hand side of the memory picture) named whatever comes immediately after the word “for”. (In this example, the name of this new variable will be v.)
    2. Then, for each element of the array, in succession:
    • Set that variable’s value to the next element of the array.
    • Execute the entire loop body. (In this example, lines 4–5.)

    In the villains example, therefore, the lines in order of execution are:

    1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 6.

    (Do you agree?)

    The memory picture changes constantly throughout any program, including those that contain loops. Let’s take a snapshot of memory as it appears immediately after executing line 3 the second time. In other words, we’ll run the program this far before hitting the pause button:

    1, 2, 3, 4, 5, 3, Freeze!!

    Memory at this instant is depicted in Figure 14.3.1. The second time we executed line 3, we set v (sometimes called the loop variable, by the way) to the second element of the array, "Ursula". We’re just about to execute line 4 for the second time. Note that the villains array is unaffected by this entire loop process: only our temporary, made-up loop variable (v) gets a new value each time.

    clipboard_eaf90d30b06993be51e5428e19a85ad7a.png

    Figure \(\PageIndex{1}\): A snapshot of memory immediately after the second execution of line 3 of the villains program.

    The complete output of the program, as you can easily deduce, is thus:

    | Here we go!

    | Oooo, Jafar is scary!

    | (Jafar has 5 letters.)

    | Oooo, Ursula is scary!

    | (Ursula has 6 letters.)

    | Oooo, Scar is scary!

    | (Scar has 4 letters.)

    | Oooo, Gaston is scary!

    | (Gaston has 6 letters.)

    | Whew!

    Don’t miss the fact that the “scary!” and “has n letters” messages were printed four times each, whereas “Whew!” only appeared once. That has everything to do with the indentation: it told Python that lines 4 and 5 were part of the loop body, whereas line 6 was just “business as usual,” taking place only after all the loop hoopla was over and done with.


    This page titled 14.3: Iterating Through an Array 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.