Paul Falkland Paul Falkland - 3 months ago 9x
Python Question

Add elements of a list together

When I use the command


I get the list
['00', '36', '52']

I would like to:

  1. First multiply the single elements with different factors

  2. Then add them together.

But what do I have to do to add them and get 88?

When I try

int(f.readline()[34:42].split()[0]) + int(f.readline()[34:42].split()[1]) + int(f.readline()[34:42].split()[2])

It goes to the next line of the file and it doesn't add the 3 numbers of the same line, which I want to add together.


f.readline() will not read the same line each time. Files have a reading position, and every time you read something that position advances.

Store the line you read in a variable first, then operate on that. You can store the result of the split in a variable too, so you don't have to keep splitting:

line = f.readline()
numbers = line[34:42].split()
result = int(numbers[0]) + int(numbers[1]) + int(numbers[2])

The important section here is to call f.readline() just the one time. You can combine the above in to a one-liner that does all the work in one go:

result = sum(int(number) for number in f.readline()[34:42].split())

which can be a bit more daunting to parse if you are new to the language, but that still reads and splits the line just once, and then processes the resulting elements from the split in a loop before adding them all together with the sum() function.