explain slice assignment to newb

Stephen Horne sh006d3592 at blueyonder.co.uk
Sat Sep 20 22:23:14 EDT 2008


On Sat, 20 Sep 2008 14:20:20 -0700 (PDT), Andrew <aetodd at gmail.com>
wrote:

>please explain this behavior to a newb:
>
>>>> a = [1,2,3,4]
>>>> b = ["a","b","c","d"]

>>>> a[0:2] = b[0:2]

The slice [0:2] represent positions 0 <= x < 2
Replaces the [1, 2] from [1, 2, 3, 4] with ['a', 'b']
Result: a = ['a', 'b', 3, 4]

>>>> b[2:4] = a[2:4]

The slice [2:4] represent positions 2 <= x < 4
Replaces the ['c', 'd'] from ['a', 'b', 'c', 'd'] with [3, 4]
Result: b = ['a', 'b', 3, 4]

>>>> a
>['a', 'b', 3, 4]
>>>> b
>['a', 'b', 3, 4]

Correct




More information about the Python-list mailing list