Skip to main content

Section 11.15 Worked Example: Lists - Find Value

Subgoals for Evaluating Lists.

  1. Declaring and initializing a list
    1. Set up a one dimensional table (i.e., one row) with 0 to size - 1 elements.
    2. Upon instantiation of a list, all elements contain values from the initializer list (i.e., the list of values inside the square brackets). If no initializer list is provided, the list is empty.
  2. Determining access, slicing, changing, adding, or whole list actions.
    1. Determine the list name and the action to be performed.
    2. If the list is on the left hand side of an assignment statement WITHOUT square brackets, it is a Whole List Action for List Assignment.
    3. If the list is on the left hand side of an assignment statement WITH square brackets, it is a Changing value of a List Element.
    4. If the append or insert method is being used on an instance of a list, it is an Adding a Value to a List Element.
    5. If the list is an expression WITHOUT square brackets, it is a Whole List Action for Passing a List as an Argument.
    6. If the list is an expression WITH square brackets, then check if there is a colon in the square brackets. If there is a colon inside of the square brackets, it is a Slicing Multiple Values from a List. Otherwise, it is an Accessing List Element.
  3. Accessing list element
    1. Determine value of index for element to be accessed; a positive value if counting from the beginning, or a negative value if counting from the end.
    2. listName[index] returns value stored at that index.
    3. Index must be between 0 and len(listName)-1, inclusive, or a negative value; otherwise an IndexError exception occurs at runtime.
  4. Slicing multiple values from a list
    1. Determine the range of indexes for the elements to be sliced
    2. listName[startIndex:endIndex] returns a new list containing the elements from startIndex to endIndex-1 (inclusive)
    3. Negative numbers can be used for startIndex and endIndex to count from the end of the list
    4. Omitting startIndex starts from the beginning of the list, and omitting endIndex goes to the end of the list
  5. Changing value of a list element
    1. Evaluate expression within [] brackets to determine the index of the element to be changed, and the list to change.
      Determine value of index for element to be changed; a positive value if counting from the beginning, or a negative value if counting from the end.
    2. Determine the expression of RHS (right-hand side) of the assignment statement.
    3. The lists’ value is now changed to match the value calculated from the RHS of the assignment statement.
  6. Adding a value to a list element
    1. Check whether the append or insert method is being used. Note that either way you do not use an assignment statement, it is just a method call.
    2. If append is used, the new value is added to the end of the list.
    3. If adding a value elsewhere in the list, use the insert method to add the new value at the specified index. Existing values starting from that index are shifted to the right.
  7. Traversing a List
    1. Determine the list that is being iterated over. If the expression also involves a range(len(list_name)), then the list is being traversed by index. The range function can either take one argument (the length of the list) or 3 arguments (the starting index, ending index, and step size). If the range function takes one argument, it will start at 0 and go to the length of the list - 1. If the range function takes 3 arguments, it will start at the first argument and go to the second argument - 1, incrementing by the third argument. Otherwise, if range is not used, then the list is being traversed by value.
    2. Determine the loop control variable that is being used to iterate over the list. The loop control variable will take on each value or index in the list, one at a time, depending on whether we are iterating by value or by index.
    3. The loop control variable is used to access the list element in the body of the loop. If iterating by index, the loop control variable is used as an index to access or update the list element. If iterating by value, the loop control variable is used directly to access the list element (no updates are possible).
    4. The list can also be added to with the append or insert methods. The append method adds a new value to the end of the list, while the insert method adds a new value at the specified index. Existing values starting from that index are shifted to the right.
  8. Whole list actions
    1. Passing a list as an argument
      1. Determine that the entire list must be passed as an argument to a method by consulting documentation.
      2. When calling a function, put variable name that represents the list as an argument in the method call. Remember that when passing a list as an argument that changes made by the function to the list are persistent. The list itself is not copied, so the function does not have its own copy of the list. However, the one exception to this is if you assign the argument to reference a different list in memory; then you will no longer be modifying the original list.
    2. List Assignment
      1. Determine that the reference to the list needs to be changed, not just its contents.
      2. The LHS of the assignment is the list reference needing to be changed.
      3. The RHS of the assignment is the new list reference.

Subsection 11.15.1

Problem: Assume that the integer list alpha has been properly declared and initialized with non-zero values, and that the variable target is an integer. What does this code accomplish? How would you describe the value in loc?
loc = -1
found = False
for i in range(len(alpha)):
    if not found and alpha[i] == target:
        loc = i
        found = True

Subsection 11.15.2 SG1: Declaring and initialization of list

There is no explicit declaration or initialization of an list within the code. However, the instructions describe that the list alpha has been properly initialized with non-zero values.
This figure shows a table with 6 columns and 2 rows. The top row is labeled with the indexes of the list, and the bottom row is labeled with the values of the list, which are currently blank. The first index is 0, and the last index is size-1.
Figure 11.15.1.
  • alpha is a list of integers and has value, but we don’t know what those values are.
  • however, we can still diagram a representation of this list.

Subsection 11.15.3 SG2: Determine access or action

Within the loop, we are accessing list elements.

Subsection 11.15.4 Evaluating code

loc = -1
found = False
The first two lines are declaring an integer variable (loc) and assigning it a value of -1. This variable will represent the "location" of the target variable, if found. A second variable, found, is declared and given an initial value of False. This variable represents whether or not we have located the target within the list.
for i in range(len(alpha)):
    if not found and alpha[i] == target:
        loc = i
        found = True
  • This loop has index i go from 0 to len(alpha) - 1 (<length) by increments of 1.
  • Then we check whether we have not yet found the value in the list, and that the value at alpha[i] is compared to the value of target.
  • If the value at alpha[i] is equal to target, then the value i is copied into loc. Additionally, the value of found is set to true, indicating that we have found the target value in the list.
Let us trace with a sample list and assume the value of target is 15.
This figure shows a table with 6 columns and 2 rows. The top row is labeled with the indexes of the list, and the bottom row is labeled with the values of the list. The first index is 0, and the last index is size-1. The values row is now populated with the values 12, 22, 8, 15, 2.
Figure 11.15.2.
The first statement, loc = -1 gives loc a temporary default value (which will also indicate if the value is not found in the list). The second statement, found = false gives found establishes that we have not yet found the target value in the list.
Then a for-loop is used to traverse the list and compare each element to target. The chart below uses one line to represent the memory and comparisons during each iteration of the loop, starting when i has a value of zero.
Table 11.15.3. Example Trace of Find
i alpha[i] target alpha[i] == target loc found
0 12 15 False -1 False
1 22 15 False -1 False
2 8 15 False -1 False
3 15 15 True 3 True
4 2 15 False 3 True
When we find the target value in the list, we store the index of where the value was found into the variable loc. We also update the variable found to True, indicating that we have found the target value in the list.
The last iteration of the loop is when i is 4, and the value of found is True. Therefore, the if statement will not even evaluate the expression alpha[i] == target because the first part of the if statement is false.
Some questions to consider:
  1. What would happen if the target value is not in the list?
    Answer.
    Then the selection statement is never true, and loc is never changed from its initial value of -1.
  2. Why is -1 a potentially problematic initial value for loc?
    Answer.
    The -1 indicates that the target value was not found in the list. If loc is never changed from -1, then we know that the target value was not found in the list. This requires everyone to know that -1 is a special value that indicates the target was not found, and not the last index of the list.
  3. What would happen if there were 2 occurrences of the target value in the list?
    Answer.
    The loop does not end when the target value is found, so no additional occurrences would be evaluated. The first occurrence would be stored in loc, and the loop would continue until the end of the list. The second occurrence would be ignored, and loc would not be updated.
What does this code accomplish?
Answer.
loc contains the index of the first occurrence of target in the list alpha or -1 if target is not in the list.

Subsection 11.15.5 Practice Pages

You have attempted 1 of 1 activities on this page.