I'm having a very specific problem that I could not find the answer to anywhere on the web. I'm new to python code (C++ is my first language), so I'm assuming this is just a semantic problem. My question is regarding objects that are declared inside the scope of a for loop.
The objective of this code is to create a new temporary object inside the for loop, add some items to it's list, then put the object into a list outside of the for loop. At each iteration of the for loop, I wish to create a NEW, SEPARATE object to populate with items. However, each time the for loop executes, the object's list is already populated with the items from the previous iteration.
I have a bigger program that is having the same problem, but instead of including a massive program, I wrote up a small example which has the same semantic problem:
#Test
class Example:
items = []
objList = []
for x in xrange(5):
Object = Example()
Object.items.append("Foo")
Object.items.append("Bar")
print Object.items
objList.append(Object)
print "Final lists: "
for x in objList:
print x.items
By the end of the program, every item in objList (even the ones from the first iterations) contains
["Foo","Bar","Foo","Bar","Foo","Bar","Foo","Bar","Foo","Bar"]`
This leads me to believe the Example (called Object in this case) is not recreated in each iteration, but instead maintained throughout each iteration, and accessed every time the for loop continues.
My simple question; in python, how to I change this?