[Tutor] Why does L[3:2] =['test'] differ from L[3]=['test']

Michael P. Reilly arcege@shore.net
Thu, 9 Nov 2000 07:46:22 -0500 (EST)


> 
> If a list L=[1, 2, 3, 4, 5]
> 
> then L[3:2]=['test'] yields -> [1, 2, 3, 'test', 5]
> 
> however, L[3]=['test'] yields -> [1, 2, 3, ['test'], 5]
> 
> Why do the results differ?  (one inserts a string into the list, but the
> other inserts a list into the list.)
> 
> Roger Mallett

Hi Roger,

The difference is between "indexing" and "slicing".  Specifying a range
of indices in a sequence will return a subsequence.

>>> L = [ 1, 2, 3, 4, 5 ]
>>> L[3:2]
[]
>>> L[3:4]
[4]
>>> L[3]
4
>>> L[3:]
[4, 5]
>>>

Notice the difference in the value returned by L[3:4] (a slice) and
L[3] (an index), the first returns a list containing an element, the
second returns the element itself.  When you assign, you will be
replacing that part of the list.  For an index, just the element is
changed; for a slice, the subsequence is replaced.  It is important to
also notice that L[3:2], where the first index is greater than or
equal to the second index, will return an empty list - because you are
looking _between_ the elements.

>>> L[3] = 'spam'
>>> L
[1, 2, 3, 'spam', 5]
>>> L[3] = [2, 3]
>>> L
[1, 2, 3, [2, 3], 5]
>>> L[3:4] = [2, 3]
>>> L
[1, 2, 3, 2, 3, 5]
>>> L[3:2] = ['eggs', 'spam']
>>> L
[1, 2, 3, 'eggs', 'spam', 2, 3, 5]

In the second assignment (using an index) a list is being set, so the
list contains a sublist.  In the third (using a slice), the sublist
is replaced with two elements, instead of one (length increases by one).

Also notice that the assignment to the slice that was _between_
elements, L[3:2] (or L[3:3]), inserts new elements instead of replacing
them.

  -Arcege

References:
* Python Tutorial, section 3.1.4 Lists
<URL:http://www.python.org/doc/current/tut/node5.html>
* Python Library Reference, section 2.1.5.4 Mutable Sequence Types
<URL:http://www.python.org/doc/current/lib/typesseq-mutable.html>
* Python Reference Manual, section 5.3.3 Slicings
<URL:http://www.python.org/doc/current/ref/slicings.html>
* Python Reference Manual, section 6.3 Assignment statements
<URL:http://www.python.org/doc/current/ref/assignment.html>

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------