Is it possible to get the reference of one element out of a list?
I know how to reference a complete list to another list:
a = [1,2,3]
b = []
b = a
a[1] = 3
print (b) #b is now [1, 3, 3]
But how can I get the reference to one element? For example:
a = [1,2,3]
b = []
b = a[1]
a[1] = 3
print (b) #b is now 2, but I want the value 3 like it is in a[1]
Or is there another solution for this problem in python?
It's not possible, because integers are immutable, while list are mutable.
In b = a[1]
you are actually assigning a new value to b
Demo:
>>> a = 2
>>> id(a)
38666560
>>> a += 2
>>> id(a)
38666512
You can like this,
>>> a = [1,2,3]
>>> b = a
>>> a[1] = 3
>>> b
[1, 3, 3]
>>> a
[1, 3, 3]
>>> id(a)
140554771954576
>>> id(b)
140554771954576
You can read this document.
As jonrsharpe said, you can do what you want by using mutable elements in your list, eg make the list elements lists themselves.
For example
a = [[i] for i in xrange(5)]
print a
b = a[3]
print b[0]
a[3][0] = 42
print a
print b[0]
b[:] = [23]
print a
print b
output
[[0], [1], [2], [3], [4]]
3
[[0], [1], [2], [42], [4]]
42
[[0], [1], [2], [23], [4]]
[23]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With