Search code examples
pythonpython-3.xlistsum

How to sum a bunch of variables?


Suppose we have 1000 variables:

a_1 = 4
a_2 = 6
.
.
.
a_1000 = 76

What would be the best/most efficient way to sum these variables? Would something like the below work:

  sum_all_list = []
    for i in range(1001):
        sum_all_list.append(globals()['a_{}'.format(i)])
  sum_all = sum(sum_all_list)

Solution

  • You can use the dir() and eval() functions:

    a_1 = 4
    a_2 = 6
    a_3 = 5
    a_4 = 2
    a_8 = 5
    a_1859 = 20
    varList = dir()
    sum = 0
    for var in varList:
      if "a_" in var:
        sum += eval(var)
    
    print(sum)
    

    Resulting output:

    42