The best way to demonstrate is through a basic code example:
aaa = 0
bbb = 0
objects_list = [aaa,bbb,aaa,bbb]
for obj in objects_list:
obj += 1
print(aaa)
print(bbb)
I understand that this way when creating the loop, the list is read like this:
objects_list = [0,0,0,0]
The print Terminal is:
0
0
The expected output in the terminal prints would be:
2
2
I’d like to recreate this here but in a loop:
aaa += 1
bbb += 1
aaa += 1
bbb += 1
Is there any way to create a list with object name instead of their values?
>Solution :
Python’s int is immutable. What you are asking is saving a "pointer" to the list. This is impossible for a integer, but needs an object. Here is an example how objects work:
class ValueWrapper(object):
def __init__(self, value):
self.value = value
def __iadd__(self, x):
self.value += x
def __str__(self):
return str(self.value)
aaa = ValueWrapper(0)
bbb = ValueWrapper(0)
objects_list = [aaa,bbb,aaa,bbb]
for obj in objects_list:
obj += 1
print(aaa)
print(bbb)
Above codes give results
2
2