-3

when I am trying to append a list, it's working weirdly. Suppose this is my code:

a = [1]
b = a
c = a

def func(a):
    a.append([50])

Here is the output:

a
[1]    
b
[1]
c
[1]

func(c)
c
[1,50]  # good till now

But now when I try to print a or b, I should get just [1] right? But no, here's what I get:

b
[1,50]

Please explain...

David
  • 6,462
  • 2
  • 25
  • 22
honey
  • 51
  • 1
  • 1
  • 7

1 Answers1

0

Here 'b' and 'c' have reference of 'a'. Since 'a' is a list and is mutable, any changes to 'a' will also reflect in 'b' and 'c'.

to make a copy of object, use

import copy
a=[10]
b= copy.deepcopy(a)
c= copy.deepcopy(a)

Now pass 'a', 'b' or 'c' to the function, you will get separate values for each of them

Cheers

Namit Singal
  • 1,506
  • 12
  • 26