I have the following code and I’m wondering why it returns the same list instead of a copy:
x = [2,1,3]
y = x
y.sort()
print y
print x
Why does this return the same sorted list?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because it’s modified in-place.
Python lists have reference semantics, meaning that when you assign a list to another variable, they’re actually pointing at the same list.
If you want to make a copy, do this:
The slice notation does cause the list (in this case, the entire list, though you can make a small modification to ask for a particular sublist) to be copied.