-2

I am defining a list and referring it to another variable. But when assigning variable to list in two different way and when printing variable then getting different values.

Anyone can explain why the result is different in both cases.

x=[1,2,3,4]
y=x
x+=[7]
print("Output 1 is :" ,x, y)
x=x+[6]
print("Output 1 is :" ,x, y)

Output 1 is : [1, 2, 3, 4, 7] [1, 2, 3, 4, 7]
Output 1 is : [1, 2, 3, 4, 7, 6] [1, 2, 3, 4, 7] ```


  • 3
    Does this answer your question? [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – GPhilo Jan 20 '20 at 11:06
  • What is `x` to begin with? What output do you get? What output did you expect? Please take some time to read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jan 20 '20 at 11:07
  • x=[1,2,3,4] y=x x+=[7] print("Output 1 is :" ,x, y) x=x+[6] print("Output 1 is :" ,x, y) Output 1 is : [1, 2, 3, 4, 7] [1, 2, 3, 4, 7] Output 1 is : [1, 2, 3, 4, 7, 6] [1, 2, 3, 4, 7] – kushal gupta Jan 20 '20 at 11:17

2 Answers2

0

The + operator always returns a newly allocated object. However, the += operator modifies the object in-place if it is mutable. Python lists are mutable. That's why, x+=[7] being in place, results same for both x and y, but, x=x+[6] doesn't. You might want to have a look at this link.

NixMan
  • 543
  • 4
  • 9
0

there are three type of copy in python. when you use "=" you need to know what does it do. please read this https://realpython.com/copying-python-objects/ to understand how it works

Arman Karimi
  • 11
  • 1
  • 6