Skip to content

5.5 For Loops

  • A common programming task is to access all of the elements in a container. Ex: Printing every item in a list.
  • A for loop statement loops over each element in a container one at a time, assigning a variable with the next element that can then be used in the loop body
  • The container in the for loop statement is typically a list, tuple, or string

5%205%20For%20Loops%20117b28b3dd3944a48f42c1be7daa3a95/Untitled.png

  • The variable in the for loop is created with the for loop statement

5%205%20For%20Loops%20117b28b3dd3944a48f42c1be7daa3a95/Untitled%201.png

  • For sequence types like lists and tuples, the assignment order follows the position of the elements in the container, starting with position 0
  • Iterating over a dictionary using a for loop assigns the loop variable with the keys of the dictionary. The values can then be accessed using the key:

    5%205%20For%20Loops%20117b28b3dd3944a48f42c1be7daa3a95/Untitled%202.png

  • A for loop can also iterate over a string. Each iteration assigns the loop variable with the next character of the string. Strings are sequence types just like lists, so the behavior is identical (leftmost character first, then each following character).

5%205%20For%20Loops%20117b28b3dd3944a48f42c1be7daa3a95/Untitled%203.png

For Loop Examples

  • The program below uses an additional variable to sum list elements to calculate weekly revenue and an average daily revenue.

5%205%20For%20Loops%20117b28b3dd3944a48f42c1be7daa3a95/Untitled%204.png

  • A for loop may also iterate backwards over a sequence, starting at the last element and ending with the first element, by using the reversed() function to reverse the order of the elements.

5%205%20For%20Loops%20117b28b3dd3944a48f42c1be7daa3a95/Untitled%205.png