Reputation: 2496
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)
Upvotes: 1
Views: 134
Reputation: 12773
If you don't need the list the question is trivial, because you simply need
total += value
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.
class mylist(list):
tot = 0
def append(self, value):
super(mylist, self).append(value)
self.tot += value
Example usage
#!/usr/bin/python
class mylist(list):
tot = 0
def append(self, value):
super(mylist, self).append(value)
self.tot += value
a = mylist()
a.append(1)
a.append(20)
print a.tot
print a
output:
21
[1,20]
Upvotes: 1
Reputation: 49846
This line is your problem:
my_list = sum([])
This returns the integer 0
. Just initialise your list:
my_list = []
And append to that.
If you also want to keep a running total, have another variable for the total:
my_total = 0
my_total += new_number
And have a single method to add new integers to the total and append them to the list.
Upvotes: 0