Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does [:] work in python?

Tags:

python

copy

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?

like image 805
TheFoxx Avatar asked Feb 21 '23 17:02

TheFoxx


2 Answers

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.

like image 158
Chris Eberle Avatar answered Feb 23 '23 06:02

Chris Eberle


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).

like image 40
Levon Avatar answered Feb 23 '23 08:02

Levon