0

suppose I have a list: x=[1,2,3]

I want to make a copy of it: y=x

I want to delete the first element from y: del y[0]

Now y only has 2 elements: [2,3]

BUT

x also has 2 elements too!!

Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x=[1,2,3]
>>> y=x
>>> del y[0]
>>> x
[2, 3]
>>> y
[2, 3]
>>> 

Why is this? And how do i delete elements from y without effecting x?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Qwertford
  • 1,039
  • 2
  • 14
  • 25
  • Is it a duplicate if the answer to two questions are same, but the two questions are different? – ababuji Aug 10 '18 at 06:05
  • 1
    @ivand58 no, *there was no copy at all*. Any copy would do in this case, shallow or deep. `y=x` is not a copy in Python, it is assignment, and assignment doesn't copy. – juanpa.arrivillaga Aug 10 '18 at 06:12
  • 1
    @Abhishek there are certain types of questions that appear so frequently that they have sort of settled on canonical duplicates among the community, even if they aren't exact duplicates. – juanpa.arrivillaga Aug 10 '18 at 06:15
  • @juanpa.arrivillaga Okay! Just wanted to know. I'm sort of new here too – ababuji Aug 10 '18 at 06:31
  • @Abhishek no problem. It's definitely a judgement call. That's why people can vote on duplicates and vote on re-opening. It's a team effort around here. – juanpa.arrivillaga Aug 10 '18 at 06:33

0 Answers0