1

I am new in python, so i used to practice some. I tried;


>>> x = [1, 2, 3, 4]
>>> y = x

>>> for i in range(0, len(x)):
...     y[i] = x[i]**2
...
>>> y
[1, 4, 9, 16]
>>> x
[1, 4, 9, 16]

My problem : I can't understand why x is changed,too.

I just expected y like this : y = [1, 4, 9, 16] (yes, it works in right way)

But, you see, x is also changed : x = [1, 4, 9, 16] (this makes me embarrassing)

How can i fix my mistake?

yudhiesh
  • 6,383
  • 3
  • 16
  • 49
ELLO
  • 21
  • 3

3 Answers3

2

When you do y = x, they are alias to the same objects in Python.

Try this if you don't want x to be changes when y changes:

x = [1, 2, 3, 4]
y = x.copy()

for i in range(0, len(x)):
    y[i] = x[i]**2
print(x)
print(y)
Roy Cohen
  • 1,540
  • 1
  • 5
  • 22
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
2

You would have to make a shallow copy of the variable x.

>>>x = [1, 2, 3, 4]
>>>y = x[:]

>>> for i in range(0, len(x)):
...     y[i] = x[i]**2
...
>>> y
[1, 4, 9, 16]
>>> x
[1, 2, 3, 4]
yudhiesh
  • 6,383
  • 3
  • 16
  • 49
1

In the second line, y = x, you made x and y point to the same list, so when you mutated y, it mutated x also. To fix this simply change that line to y = []. But now we got a different problem, IndexError: list assignment index out of range, to fix this, instead of assigning to y[i], we'll use y.append:

x = [1, 2, 3, 4]
y = []
for i in range(0, len(x)):
    y.append(x[i]**2)

Output:

x == [1, 2, 3, 4]
y == [1, 4, 9, 16]

Note that with this we no longer need i, only x[i], so we can iterate over x instead:

for item in x:
    y.append(item**2)
Roy Cohen
  • 1,540
  • 1
  • 5
  • 22
  • It makes another problems: ``` Traceback (most recent call last): File "", line 5, in IndexError: list assignment index out of range ``` – ELLO Jan 26 '21 at 07:24
  • @ELLO I've edited the answer to acount for that, refresh your page. – Roy Cohen Jan 26 '21 at 07:28