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

jfong at ms4.hinet.net jfong at ms4.hinet.net
Wed Apr 12 21:01:01 EDT 2017


Peter Otten at 2017/4/12 UTC+8 PM 8:13:53 wrote:
> I should add that you can write
> 
> >>>> 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]]
> > 
> 
> idiomatially as
> 
> >>> lr = [[1], [0]]
> >>> [inner + tail for tail in [[1], [0]] for inner in lr]
> [[1, 1], [0, 1], [1, 0], [0, 0]]
> 
> Note that there is a difference -- the resulting list does not share any 
> lists with the original `lr` as concatenating two lists produces a new one:
> 
> >>> a = [1]
> >>> b = [2]
> >>> c = a + b
> >>> a is c
> False
> >>> b is c
> False

I was a little embarrassed when looking at my codes. It may take me a long time to get used to thinking in the "Pythonic" way:-( But definitely I have learned much from this forum:-)



More information about the Python-list mailing list