'Why is the new list still the same as the old list after sorting? [duplicate]

l=[3,2,1]
x=l
x.sort()
x==l
True

The above occurrence happens in Python. I am confused since after applying sort on x, x should become the list [1,2,3] which is different from [3,2,1].



Solution 1:[1]

When you create x and assign it to l, you are not creating a new list. When you do that, you're making l point to the value of x. This is different when you do this with integers, for example, where

a = 1
b = a
a = 2
print(b)

outputs 1.

Try printing x and l separately to check this. x has a value of [1, 2, 3], and so does l.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robo