[Tutor] s[len(s):len(s)] = [x] ??
drumond.douglas at gmail.com
Mon Jun 30 23:39:34 CEST 2008
Thanks, Ryan, for detailed explanation;
I'm learning Python now, too, so I don't know exactly how stuff works.
On Mon, Jun 30, 2008 at 18:33, Lie Ryan <lie.1296 at gmail.com> wrote:
>> You can do it with slice assignment too:
>> >>> a = [1, 2, 3, 4]
>> >>> a[1:3] = [[7, 8]]
>> >>> a
>> [1, [7, 8], 4]
>> Now, which way is better? The answer depends on context. The best
>> way to write it is in the manner that it makes the most sense to
>> someone reading your program (including you, several years later)!
> I think that the current behavior in python makes sense according to
> python's slicing model: which is cursor-like behavior. List slice (and
> indexing) in python is done on the model of a cursor:
> 0 1 2 3
> | A | B | C | D |
> -4 -3 -2 -1 0
> Cursor-like behavior of list in python is similar to the "typing
> cursor", if you, for example, highlights letter B and C (i.e. taking
> slice [1:3]) then pasted another string of letters, the result would be
> the pasted string replaced the highlighted object (i.e. the slice is
> gone and the inserted list become a sublist that replaced the sliced
> one). If the pasted list have been inserted instead, it wouldn't fit the
> cursor model.
> On an aside, I'm interested in seeing how this would be parsed by python
> l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> l[2:8:2] = [...]
> It turns out that assigning to extended slice notation require that you
> to have the same length sequence on both sides, just as expected, python
> doesn't do some voodoo magic for this since: "In the face of ambiguity,
> refuse the temptation to guess" and "There should be one -- and
> preferably only one -- obvious way to do it" [import this].
> Tutor maillist - Tutor at python.org
More information about the Tutor