Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the reference of a List element?

Tags:

python

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?

like image 510
char0n Avatar asked Oct 31 '22 14:10

char0n


2 Answers

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.

like image 177
Adem Öztaş Avatar answered Nov 15 '22 03:11

Adem Öztaş


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]
like image 20
PM 2Ring Avatar answered Nov 15 '22 05:11

PM 2Ring