3

Something very strange is happening to me. when i write this code down :

a = [3,2,4]
b = a
a.sort()
print(a)
print(b)

The variable "b" must be [3,2,4] and "a" must be [2,3,4]. But this result came out :

[2, 3, 4]
[2, 3, 4]

Why did it sort both of them? I think it only happens to lists,because I tried to write the code below :

dots = dotsDetecter(param).getDots()
wholeDots = dots 

The variable "dots" is gonna be a list but after that whatever I do to the "dots" list, wholeDots variable changes exactly like dots.

Does anybody now why it is happening?

1 Answers1

7

b = a does not instantiate a new list, b is just an alias of a. So every operation on a will also affect b. You should do something like this:

def main():
    a = [3, 2, 4]
    b = list(a) # create new list initialized with a values
    a.sort()
    print(a)
    print(b)
Paolo Irrera
  • 253
  • 1
  • 10