Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Built-in Functions Common to Most Data Structures
11. index() – exercise
Summary

Instruction

Excellent! Let's do one more exercise with index().

Exercise

Write a function named find_average_first_index(input_list, input_letter) that accepts a list of strings and a single letter.

  1. The function should return the average index of the first occurrence of the input_letter among all strings in the list that contains the input_letter.
  2. If a list element does not contain the given letter, skip it. Do not add it to the number of elements when calculating the average.
  3. If no list element contains the given letter, return -1.

Example: for the sample_list in the template code and the input letter 'o', the function should return 6.33:

  • 'Black Mirror': 'o' at index 10
  • 'Breaking Bad': no letter 'o' (ignored)
  • 'Stranger Things': no letter 'o' (ignored)
  • 'The Leftovers': 'o' at index 8
  • 'How I Met Your Mother': 'o' at index 1
(10 + 8 + 1) / 3 = 6.33

Stuck? Here's a hint!

Create two temporary variables, sum_indexes and counter. Iterate over the list and use a try-except block with index().