Matan Ran
Matan Ran

Reputation: 33

How to assign a value in a list to an object in python

I have the following statesments:

A = "s"
B = ["1", "2", "3"]

I want to get the object "A" when I am printing B[2], e.g: print(B[2]), and the answer will give me "A" with a reference to the value of A..

How can I do it in python?

Any suggestion would be appreciated

Thank you all.

The same question in another manner:

I have seen this in the forum:

>>>foo = 'a string'
>>>id(foo) 
4565302640
>>> bar = 'a different string'
>>> id(bar)
4565321816
>>> bar = foo
>>> id(bar) == id(foo)
True
>>> id(bar)
4565302640

But if I have:

>>> foo = "a string"
>>> id(foo)
36591240
>>> bar = ["1", "2", "3"]
>>> id(bar)
39186840
>>> bar[2] = foo
>>> id(bar) == id(foo)
Flase

How can I assign a value in a list to match a different obect?

Upvotes: 1

Views: 1805

Answers (3)

Aviv Bar-el
Aviv Bar-el

Reputation: 81

TL;DR B[2] = A

You need to understand that in python string objects are immutable objects, This mean those objects cannot be changed and they behave different from mutable objects.

So after defining a string, an object is created. but because this object is immutable, If you assign other variable pointing to the same object, when you will change the original variable, you are creating a new object and not changing the object you created.

for mutable objects the assign is just like you will normally do for example look at this:

In [1]: A = ['s']

In [2]: B = ['1','2','3']

In [3]: B[2] = A

In [4]: id(B[2]) == id(A)
Out[4]: True

And for your example you can define a new class instead of string

In [1]: class MutableString:
   ...:     def __init__(self, value):
   ...:         self.value = value
   ...:     def __str__(self):
   ...:         return self.value
   ...:     def __repr__(self):
   ...:         return repr(self.value)
   ...:

In [2]: A = MutableString('foo')

In [3]: B = ['1', '2', '3']

In [4]: B[2] = A

In [5]: print(B)
['1', '2', 'foo']

In [6]: A.value = 'bar'

In [7]: print(B)
['1', '2', 'bar']

In [8]: id(B[2]) == id(A)
Out[8]: True

Upvotes: 0

Alperen
Alperen

Reputation: 4602

I'm not sure why you do this, but defining a new list class could help:

class NewList(list):
    def __init__(self, mapping):
        self._mapping = mapping
        list.__init__(self)
        
    def __getitem__(self, key):
        item = list.__getitem__(self, key)
        return self._mapping[item]

Then, you can use it as a list after you define a mapping showing which item corresponds to which object:

A = "s"
mapping = {"3": A}

B = NewList(mapping)
B.extend(["1", "2", "3"])  

print(B[2])

Output:

s

Upvotes: 0

Gvantsa
Gvantsa

Reputation: 59

What you need to have is id(bar[2]) == id(foo). This will return True.

Generally lists are mutable so you can assign whatever value you want particular list element to be.

Upvotes: 2

Related Questions