-1
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].

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
cg21
  • 1
  • Maybe [this post](https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort) can help you understand – Christophe Mar 05 '22 at 11:19
  • 3
    `x` does become what you expect, the problem is that `l` does too. – Passerby Mar 05 '22 at 11:19
  • @Passerby Why does it modify l? Since x was only initially defined as equal to l, but the sorting was only done on x. – cg21 Mar 05 '22 at 11:26
  • 1
    The issue is not with `.sort`, but with `x=l`, which _doesn't create a different list_ as you expect. Instead, `x` and `l` are references to the same list. – Gino Mempin Mar 05 '22 at 11:28
  • *x* is merely a reference to *l*. Try *x=l.copy()* or *x=l[::]* That may help you to understand what's going on – DarkKnight Mar 05 '22 at 11:36
  • Who told you people that something like `x=l` makes a copy? Seriously, I want to know. I'm always wondering why people think that. – Kelly Bundy Mar 05 '22 at 12:18

1 Answers1

0

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.

Robo
  • 660
  • 5
  • 22