Autumn Offers - hours only!Up to 80% off on all courses and bundles.-Close


Good job! Last one to go and it's time for dictionaries!


Create a function sum_line_numbers(filename) that opens the file and sums all the numbers on each line. The function should return a list with the line sums as its elements. Call the function on the numbers.txt file and assign the result to the result variable. Assume that the file contains only numbers.

For example, if the contents of a file are:

1 1 2
3 4 14

The function should return:

[4, 1, 21]

Stuck? Here's a hint!

To open the file and read its contents line by line, use:

with open(filename) as f:
  for line in f:

You are going to need nested loops. An outer loop should iterate over lines and an inner loop should iterate over the numbers on a given line. Use the split() function to split each line into individual numbers.

Also, remember that everything read from a file is treated as a string of characters, so you have to cast every number to integer.