List slice assignment and custom sequences

Ronald Oussoren oussoren at cistron.nl
Sat Nov 2 17:40:49 EST 2002


On Saturday, Nov 2, 2002, at 20:39 Europe/Amsterdam, Erik Max Francis 
wrote:

> Ronald Oussoren wrote:
>
>> I traced this to the implementation of this feature in type 'list': It
>> requires that the new version of the slice is also a 'list':
>>
>>         l = [ 1, 2, 3, 4]
>>         l[1:3] = range(10)      # works fine
>>         l[1:3] = xrange(10) # raises TypeError
>>
>> Why must the RHS side of 'l[1:3] = expr()' be an instance of 'list'?
>
> Well, you want to splice one list into another.  Both have to be lists.
No, I want to replace part of a sequence by another sequence. I don't 
understand _why_ the RHS must be a list if the LHS is one. It doesn't 
even allow a tuple, even though tuples can be used instead of lists in 
almost all code that treats the sequence as read-only.

> To convert any sequence S to an actual list, use the list builtin:
>
> 	list(S)
>
> So you'd just write your problem code as
>
> 	l[1:3] = list(xrange(10))
>
> Although in this case, needless to say, range(10) would make a great
> deaal more sense.
Sure, but xrange was just an example. FYI the actual type is NSArray 
(http://pyobjc.sourceforge.net). We'd like to make this type act as 
closely as possible like a normal list to avoid unnecessary conversions 
to/from python types.

Ronald





More information about the Python-list mailing list