Why does changing one list, change another - Python

0 votes

I have recently started learning python. I have the following code:

x = []
y = x
y.append(10)

The issue here is, I am appending the variable y but for some reason, variable x is also getting appended. Why is this happening? 

Jul 25, 2019 in Python by Aleesha
51 views

1 answer to this question.

0 votes
Hey @Aleesha, here when you write x=y, you're not creating a copy of x and assigning that to y. Instead, it creates a new variable y and a reference to the object x is passed. This means that there is only one object (the list), and both x and y refer to it. Hence changing y will change x also.
answered Jul 25, 2019 by Kanika

Related Questions In Python

0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

950down voteaccepted It's because any iterable can be ...READ MORE

answered May 15, 2018 in Python by aryya
• 7,370 points
119 views
0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

This is because join is a "string" ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 57,550 points
138 views
+1 vote
1 answer

Why does x,y = zip(*zip(a,b)) work in Python?

I'm extremely new to Python so this ...READ MORE

answered Aug 23, 2018 in Python by Priyaj
• 57,550 points
192 views
0 votes
1 answer

How do I append one string to another in Python?

If you only have one reference to ...READ MORE

answered Oct 22, 2018 in Python by SDeb
• 13,250 points
94 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,201 views
0 votes
0 answers
+4 votes
6 answers
0 votes
2 answers

Is it possible to call one python script from another Python Script?

Hello,  To call one python script from another ...READ MORE

answered Jun 30 in Python by Niroj
• 44,420 points
3,925 views
0 votes
1 answer

How to write content of one file to another file in Python?

The following code snippet might solve your ...READ MORE

answered Aug 26, 2019 in Python by Neel
• 3,010 points
83 views