What is the difference between x[:]=y and x=y[:]?

alister alister.ware at ntlworld.com
Wed Apr 12 04:33:13 EDT 2017


On Wed, 12 Apr 2017 01:08:07 -0700, jfong wrote:

> I have a list of list and like to expand each "list element" by
> appending a 1 and a 0 to it. For example, from "lr = [[1], [0]]" expand
> to "lr = [[1,1], [0,1], [1,0], [0,0]]".
> 
> The following won't work:
> 
> Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32
> bit (Intel)] on win32 Type "help", "copyright", "credits" or "license"
> for more information.
>>>> lr = [[1], [0]]
>>>> lx = []
>>>> for i in range(len(lr)):
> ...     lx[:] = lr[i]
> ...     lx.append(0)
> ...     lr[i].append(1)
> ...     lr.append(lx)
> ...
>>>> lr
> [[1, 1], [0, 1], [0, 0], [0, 0]]
>>>>
>>>>
> But the following does:
> 
>>>> lr = [[1], [0]]
>>>> lx = []
>>>> for i in range(len(lr)):
> ...     lx = lr[i][:]
> ...     lx.append(0)
> ...     lr[i].append(1)
> ...     lr.append(lx)
> ...
>>>> lr
> [[1, 1], [0, 1], [1, 0], [0, 0]]
>>>>
>>>>
> After stepping through the first one manually:
> 
>>>> lr = [[1], [0]]
>>>> lx[:] = lr[0] lx.append(0)
>>>> lx
> [1, 0]
>>>> lr[0].append(1)
>>>> lr
> [[1, 1], [0]]
>>>> lr.append(lx)
>>>> lr
> [[1, 1], [0], [1, 0]]
>>>>                   
>>>>                   
> So far so good...
> 
>>>> lx[:] = lr[1] lx.append(0)
>>>> lx
> [0, 0]
>>>> lr[1].append(1)
>>>> lr
> [[1, 1], [0, 1], [0, 0]]
>>>>
>>>>
> Woops! What's wrong?
> 
> --Jach Fong

1st never* use range to step through items in a list
if you need the index as well as the item use Enumerate

    a=[[1],[2]]
    for i,x in enumerate(a):
        a[i].append(0)
    print a


* like all rules an experienced programmer may find a usage case where it 
may be broken



-- 
While money doesn't buy love, it puts you in a great bargaining position.


More information about the Python-list mailing list