Find out how to quickly and easily loop through a list in Python 3 and determine the average value.
Starting with a simple list of prices:
prices = [5.33, 4.55, 2.34, 6.45]
We want to find the average of these values, giving us the average price of the list items.
We’ll create a for loop to loop through each item in the list:
for price in prices:
Please note that ‘price‘ is a temporary variable that we create to store one of the values in the list each time the loop runs. In this case the word ‘price’ makes sense, but it could in reality be anything.
Then we’ll add in the code that we want to repeat:
for price in prices: print('Price is ', price)
Lets create a new variable which will store the total of the values in the list:
total = 0
And we’ll add a line to the loop which adds each of the list values to the total:
total = total + price
Then print the result:
print('Total is', total)
Lastly, outside of the loop (after it’s finished) we divide the total by the number of items in the list (using the
average = total/len(prices) print('Average is: ', average)
Putting this all together:
total = 0 prices = [5.33, 4.55, 2.34, 6.45] for price in prices: print('Price is ', price) total = total + price print('Total is', total) average = total/len(prices) print('Average is: ', average)