Python beginner running 2.7
I want to have a list which is constantly summed as new values are added to it. However, I keep getting Attribute Error: ‘int’ object has no ‘append’ function. I understand the basic problem – you can’t append to an integer – but would like to find a workaround. Do any of you have a solution?
Simplified version of my code, and then a possible solution I’d like to avoid.
my_list = sum([])
def myfunction (i):
return i
thing = myfunction (1)
my_list.append(thing)
thing2 = myfunction (2)
my_list.append(thing2)
def function_2 (a,b):
#function which uses my_list
I suppose I could do the following solution, but I would like to avoid it (interferes with existing code).
my_list = []
summed_my_list = sum (mylist)
def myfunction (i):
return i
thing = myfunction (1)
my_list.append(thing)
thing2 = myfunction (2)
my_list.append(thing2)
If you don’t need the list the question is trivial, because you simply need
at each step.
Class derived from list
If you do need both the list and the sum (which autoupdates) you could create a class derived from list such as – which should auto sum when you append to it.
Example usage
output: