简体   繁体   中英

How does [:] work in python?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM