Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to use the name of an object to a list instead of the value of that object?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading