dett
dett

Reputation: 83

Basic python. How to forbid functions to change the list?

>>> def test():
...    a.remove(1)
>>> a = [1,2]
>>> test()
>>> print a 
[2]

Why does a equal [2] rather than [1,2]?

Upvotes: 2

Views: 2361

Answers (4)

9000
9000

Reputation: 40894

List is mutable. If you pass it to a function, and the function changes it, it stays changed.

  • Use an immutable structure: tuple: a = (1,2)
  • Pass a copy of original list: b = list(a); b.remove(1) — now a and b have different contents, a hasn't changed.

Also, try not to use mutable global data. Either pass a to the function, or have a as an attribute of an object, and the function as its method.

Upvotes: 6

user225312
user225312

Reputation: 131717

Because the list a exists in the global namespace and when you call a remove on it, the value 1 is removed.

If you don't want it to be modified, simply create a new list. If you call remove on the list a, of course it going to remove the value.

Upvotes: 0

AndiDog
AndiDog

Reputation: 70208

Lists are mutable objects, they are meant to be changed. If you want to forbid changes, convert it to a tuple (e.g. a = (1, 2)) instead. Tuples are immutable, so it's not possible to change them without copying and re-assigning the variable.

Upvotes: 0

user97370
user97370

Reputation:

It's not clear what you want. Your test() function modifies the global 'a' list, so it's unsurprising that 'a' gets modified.

If you want 'test' to work on a copy of a instead directly on a, you may copy it first.

For example,

def test():
    a2 = list(a)
    a2.remove(1)

Upvotes: 2

Related Questions