- [Instructor] In this self check exercise,
we want you to go ahead and manipulate
a two-dimensional list called t.
And we've defined that list for you here.
It has two rows, and in each row we have three columns each.
Now, what we'd like you to do
with this particular list,
is first, go ahead and figure out the average
of t's elements using nested for statements
to walk your way through the list, calculate the total,
and then eventually calculate the average.
And then separately, we'd like you to do that
a little bit differently,
we'd like you to use a for statement
that displays the average of t's elements
using reductions like, sum and len
to calculate the sum of each row's elements
and the number of elements in each row respectively,
and then move on to calculate the average
as a result of all of that, as well.
So, go ahead and give that a shot,
and after you come back we'll show you the answer.
Okay, so first of all, of course,
we need to define the list
that we were talking about up above.
And the first the thing we want to do
is used nested for loops to calculate
the total and average for these elements.
So, as you can see, we've defined a couple of counters here
to help us keep track of the total of all the elements
and to keep track of the number of items there are, as well.
And we have a nested for loop,
just like we showed you in the preceding video,
but for each item this time,
we're going to add the item to the total
and we're going to increment items by one.
And again, for those of you
coming from other C-based languages,
we do not have a plus plus operator in Python.
So, let me go ahead and execute that.
And, of course, once we have the total
and the number of items,
we can calculate the average very easily
by just dividing the total by that number of items.
Now, of course, we've seen a number of reductions
in prior examples and lessons.
And so there's easier ways to implement
what we just showed you there.
Let's go ahead and rest total to zero and items to zero.
And take a look at this for loop.
This is not a nested for loop,
it's just a single for loop
that says for every row in the array t,
or in the list t, excuse me,
let's go ahead and sum up the elements within that row
and add that entire row's sum to the total.
And let's count the number of items in that row
by checking its length,
and add that to the total number of items.
And then, of course, after executing that we can calculate
total divided by items to get our average.