[Tutor] s[len(s):len(s)] = [x] ??

Jerry Hill malaclypse2 at gmail.com
Mon Jun 30 22:59:53 CEST 2008


On Mon, Jun 30, 2008 at 4:47 PM, Dick Moores <rdm at rcblue.com> wrote:
> Show me a better way?

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)!

If, conceptually, you are removing two elements from a list, then
adding a new element which is itself a list, then doing it with remove
and insert is probably best.  On the other hand, if you are picking
two elements out of the list (a slice) and replacing it with a new
sublist, then the slice assignment may make more sense to the reader.

-- 
Jerry


More information about the Tutor mailing list