Python Forum

Full Version: Reading Multiple Lists Using SUM function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

Here is the code I am trying to improve - can longer lists be read from a file and looped through and printed?

p8262 = [331, 83, 112, 111, 21, 67, 8] 
p8264 = [384, 84, 119, 74, 28, 51, 6] 
p8401 = [330, 114, 217, 81, 11, 52, 5] 

# variables to be looped 

Sum = sum(p8262) 
Sum1 = sum(p8264) 
Sum2 = sum(p8401) 

print("The sum of p8262 is " , Sum) 
print("The sum of p8264 is " , Sum1) 
print("The sum of p8401 is " , Sum2)


All the Best,
Dave
you can do all in one like:
print(f"The sum of p8262 is {sum(p8262)}")
Thanks! That works. Is there a way to read and loop through a file? Have around 300 lists.
what is the file - json? show what you have
It's a text file with 259 identical lists like so.

p8262 = [331, 83, 112, 111, 21, 67, 8]
p8264 = [384, 84, 119, 74, 28, 51, 6]
p8401 = [330, 114, 217, 81, 11, 52, 5]

...

print(f"The sum of p8262 is {sum(p8262)}")

Can just the name of the lists be assigned as a variable then I could print out the list name and sum return.

Best
this is weird file format.
you can do something like
from ast import literal_eval

with open(path_to_your_file) as f:
    for line in f:
        name, values =  line.split(' = ')
        values = literal_eval(values)
        print(f"The sum of {name} is {sum(values)}")
of course, instead of ast.literal_eval, you can parse the list yourself, i.e. after the split at =, you can remove the brackets, split at comma, convert numbers to int, and so on...
Bingo buran - thanks all, BTW this is the coolest python forum. :)