explain slice assignment to newb

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew

    explain slice assignment to newb

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

    #2
    Re: explain slice assignment to newb

    Andrew wrote:
    please explain this behavior to a newb:
    Read the section on sequence slicing in the Library Reference. Use the
    interactive interpreter or IDLE to perform experiments, like you did,
    until you understand to your satisfaction.

    Comment

    • Stephen Horne

      #3
      Re: explain slice assignment to newb

      On Sat, 20 Sep 2008 14:20:20 -0700 (PDT), Andrew <aetodd@gmail.c om>
      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

      Comment

      Working...