It copies a list right? but in the code I'm looking at its x = x[:]
which I don't understand. How can both copies be called the same thing?
The right is evaluated first, placed into a temporary variable, and x is re-assigned to the temp variable. You never see it, of course.
To answer your question "How does [:] work in python?" is a bit tricky in the context of this particular expression by itself
x = x[:]
which isn't that likely to occur as it's really like saying a = a
.
You are more likely to see something like
a = x[:]
which in simple words makes a copy of the list referred to by x
and assigns it to a
.
If you simply did
a = x
both variables would refer to the same location, and any change to either of the variables would be reflected in both.
Here is what happens if you don't use the colon notation, e.g., a = x
:
In [31]: x = range(5)
In [32]: a = x
In [33]: a
Out[33]: [0, 1, 2, 3, 4]
In [34]: x
Out[34]: [0, 1, 2, 3, 4]
In [35]: a[3] = 99 # I am making a change in a
In [36]: a
Out[36]: [0, 1, 2, 99, 4]
In [37]: x
Out[37]: [0, 1, 2, 99, 4] # but x changes too!
Compare this with a = x[:]
In [38]: x = range(5)
In [39]: a = x[:]
In [40]: a
Out[40]: [0, 1, 2, 3, 4]
In [41]: x
Out[41]: [0, 1, 2, 3, 4]
In [42]: a[3] = -99
In [43]: a
Out[43]: [0, 1, 2, -99, 4] # a changes
In [44]: x
Out[44]: [0, 1, 2, 3, 4] # x does not change
Note: @gnibbler provides a short and complete example (below in the
comments) where you might encounter x = x[:]
and in that context
that assignment would serve a useful purpose (though we don't know in what context you came across this originally).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With