0

When I run my program, it gave an error as usual. When I looked back at the code, I found the error a bit strange. I put print in the code to analyze a variable and I saw something that was total nonsense. Somehow a variable lost a value but in the code it doesn't change! I will share a sample code but same story here:

def f(a):
    a.remove(1)
    return a

list1 = [1, 2, 3]
print(f(list1))
print(list1)

in the first print you would expect an output as:

[2,3]

and in second print you would expect:

[1,2,3]

as it didn't change in the main code. Well it turns out the output is like this:

[2, 3]
[2, 3]

In my program, I went nuts trying to solve it. I debugged it and I saw that the variable changes in a function similar to f(). I thought that since in a function the program would run in scope level, it wouldn't influence a global variable like list1. So is this a bug in python or should I avoid using methods in functions?

By the way, I solved the problem by editing like:

def f(a):
    x = list(a)
    x.remove(1)
    return x

list1 = [1,2,3]
print(f(list1))
print(list1)

for some reason x=a wasn't enough so I used x=list(a)

quamrana
  • 37,849
  • 12
  • 53
  • 71
Sarper Bilazer
  • 289
  • 2
  • 6

0 Answers0