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
44 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,350 points
83 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,530 points
107 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,530 points
122 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,230 points
71 views
0 votes
1 answer
+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 756 views
0 votes
0 answers
+4 votes
6 answers
0 votes
1 answer

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

Yes it is possible. Suppose your script abc.py ...READ MORE

answered Jul 2, 2019 in Python by Arvind
• 2,980 points
151 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
56 views