Pergunta

In Perl I can say this :

> perl -e '@a=(1,2,3);$b=\@a;$$b[1]=5;print @a'
153    

@a=(1,2,3);
$b=\@a;
$$b[1]=5;
print @a

i.e. I can change the original variable @a via the reference $b. How can I do that in Python ?

=========

Sorry my mistake I was trying to delete the content of the referent array "a" via the reference "b".. and it does not seem to work. What is the correct way to delete a via b

> a = [1,2,3]
> b = a
> b
[1, 2, 3]
> b = []
> a
[1, 2, 3]

'a' still not empty i.e. I have reference to variable and I want to clean it up via the reference?

Foi útil?

Solução

All types in Python are references. That means you cannot re-assign an actual variable and expect it to change the original variable. However, you can certainly modify a variable through a "reference" which is automatically created on copy.

a = [1,2,3]
b = a
b[0] = 0
print a

Output

[0,2,3]

If you want to delete a list via a reference, you can use the other solution or do the following:

b[:] = []

Outras dicas

You can mutate a list via deletion as such:

>>> a = [1, 2, 3]
>>> b = a
>>> del b[:]
>>> b
[]
>>> a
[]    

The special syntax del b[:] is equivalent to b.__delitem__(slice(0, len(b))) - that is, it calls a method on the object that b points to, which ends up mutating that object, instead of assigning a different object to b which is what b = [] does.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top