List of Lists, Computing an Average

Screen Link:

While I understand the following code
‘’'row_1 = [‘Facebook’, 0.0, ‘USD’, 2974676, 3.5]
row_2 = [‘Instagram’, 0.0, ‘USD’, 2161558, 4.5]
row_3 = [‘Clash of Clans’, 0.0, ‘USD’, 2130805, 4.5]
row_4 = [‘Temple Run’, 0.0, ‘USD’, 1724546, 4.5]
row_5 = [‘Pandora - Music & Radio’, 0.0, ‘USD’, 1126879, 4.0]

app_data_set = [row_1, row_2, row_3, row_4, row_5]
avg_rating = (app_data_set[0][-1] + app_data_set[1][-1] + app_data_set[2][-1] + app_data_set[3][-1] + app_data_set[4][-1]) / 5


I was hoping to do it in one less line of code:
‘’’ avg_rating = ([row_1, row_2, row_3, row_4, row_5] / 5 ‘’’
and received an incompatibility error regarding types: lists and ints.

so, I tried to cast the list as an int, but that failed as well. Is this possible and I’m not seeing the correct syntax or does this need to be a two step procedure in setting a variable, then performing the calculation on the variable. Thank you!


Hi Jason, welcome to the forums!

Let’s say we have a list of just numbers: [1, 2, 3, 4, 5]. If I wanted to find the average of this list, I would need to add the numbers and divide by 5. But typing [1, 2, 3, 4, 5] / 5 doesn’t work because we aren’t telling python to add those numbers inside the list. We can’t convert the whole list to a single integer either.

For avg_rating = ([row_1, row_2, row_3, row_4, row_5]) / 5, the situation is more complicated because each of the items is already a list. So then we’re taking 5 lists and trying to divide a list of lists by 5. Python doesn’t know what to do with that.

We could, however, bypass the whole app_data_set piece of it and add the last item of each row list for the average rating:

avg_rating = (row_1[-1] + row_2[-1] + row_3[-1] + row_4[-1] + row_5[-1]) / 5

The reason we’re doing it this way is to practice accessing the items of a list, and the items from a list of lists. Later on you’re going to be working with datasets imported from a CSV, and it will become a list of lists (like app_data_set). You’ll want to know how to indexing works for this, so they start you out with a smaller example and work you up to it.

You’ll be happy to know that in a few missions you’ll be covering loops, which will make the process of finding the averages a lot simpler. You’ll also learn about creating functions, including some built-in ones that can add the numbers inside a list like [1, 2, 3, 4, 5] for you.

I hope that helps!


Thank you @april.g, great explanation! It helped a lot. =)