0

So basically I have two lists a and b and have defined them like a=b=[10] so changing one will change the other-

a=b=[10]
a[0]+=1
a
>>>[11]
b
>>>[11]

Is there a way to do this but instead make it give double of the variable? Desired output -

a=b=[10]
#some code
a
>>>[10]
b
>>>[20]
sr0812
  • 324
  • 1
  • 9

4 Answers4

1

You can create a new class that inherits from list and create a property that returns the modified values:

class new_list(list):
    @property
    def double(self):
        return [i * 2 for i in self]

        
a = new_list([10])

a.append(20)
a.append(30)
print(a, a.double)
[10, 20, 30] [20, 40, 60]

The advantage with this approach is that you still be able to use all methods from list directly.

Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
0

I'm not sure if I get what you're trying to do correctly, but something like this should work.

prop = property(lambda self: self.a * 2)
# Dynamically creating a class with a default value for `a` and `b`
Class = type('ClassName', (object,), {"a": 0, "b": prop})

c = Class()
c.a = [10]
print(c.a, c.b)  # ([10], [10, 10])
Wiggy A.
  • 496
  • 3
  • 16
0

with a=b=[0] you don't actually have two lists. The assignment just copies the reference to the list, not the actual list, so both liat 'a' and list 'b' refer to the same list after the assignment.

a=b=[10]
print(a) // [10]
b = list(a)[0] * 2 
a[0] += 1

print(a) // [11]
print(b) // [20]

To actually copy a into b you have various option simplest one would be using using the built in list() function to make a actual copy . Thank You.

  • I don't want that, I want to make it so that when I modify one of the variables, the other one is also modified – sr0812 Dec 17 '21 at 04:42
  • okay, I think you need a event system here. Idea is to listen for a value change event in list 'a' and then trigger a method which would modify list 'b' – DEBASHISROY ROY Dec 17 '21 at 05:20
  • this might be helpful https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it – DEBASHISROY ROY Dec 17 '21 at 05:21
0

Because a=b=[10] is equal to b=[10];a=b so they are the same thing with only one instance. You can just

b=[a[0]*2] 

or

b=[x*2 for x in a]
Ben
  • 141
  • 8