Assignment to slice

Discussion in 'Python' started by Rich Krauter, Jan 21, 2004.

  1. Rich Krauter

    Rich Krauter Guest

    I do not understand why python behaves the way it does
    in the following code:

    Here, Python doesn't like that I'm assigning
    out-of-range. OK. That's fine.
    >>> x = []
    >>> x[5] = 3

    Traceback (most recent call last):
    File "<interactive input>", line 1, in ?
    IndexError: list assignment index out of range

    However, the following seems very strange. Assigning
    to a slice, over non-existent array indexes, sets x[0]
    and x[1].
    >>> x[2:5] = [3,4]
    >>> x

    [3,4]
    >>> x[1000:9000] = [5]
    >>> x

    [3, 4, 5]

    Why does assigning to a slice of non-existent array
    elements fill in the array, starting with the first
    empty array position? (Acts like [].append() or
    [].extend()?)

    Why not raise an out-of-bounds exception here too?
    Wouldn't that be more consistent with the first case,
    in which I tried to assign out-of-range, and got an
    exception?

    IMO, at least the first index in the slice should be
    required to exist in the array. If not, raise an
    exception. That way, assigning to the slice fills in
    the array in a predicatable way without having to do
    len() checks first to ensure that you know where in
    the array the slice is actually going to be inserted.

    But I'm sure it is the way it is for a good reason.
    Hopefully someone can clue me in.

    Thank you in advance.

    Rich




    __________________________________
    Do you Yahoo!?
    Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
    http://hotjobs.sweepstakes.yahoo.com/signingbonus
    Rich Krauter, Jan 21, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. James Henderson

    Re: Assignment to slice

    James Henderson, Jan 21, 2004, in forum: Python
    Replies:
    2
    Views:
    272
    James Henderson
    Jan 22, 2004
  2. Rich Krauter

    RE: Assignment to slice

    Rich Krauter, Jan 21, 2004, in forum: Python
    Replies:
    6
    Views:
    332
    sambo
    Jan 23, 2004
  3. Jens Lippmann

    Slice assignment for strings?

    Jens Lippmann, May 25, 2004, in forum: Python
    Replies:
    4
    Views:
    449
    Paul Rubin
    May 25, 2004
  4. Andrew
    Replies:
    2
    Views:
    223
    Stephen Horne
    Sep 21, 2008
  5. Daku
    Replies:
    0
    Views:
    697
Loading...

Share This Page