Fighting slice syntax for attaching part of a list to a list item

Suppose I have a simple Python list:

>>> l=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Now suppose I want to combine l[2:6]with one element like this:

>>> l
['0', '1', '2345', '6', '7', '8', '9']

I can do this step by step in a new list, for example:

>>> l2=l[0:2]
>>> l2.append(''.join(l[2:6]))
>>> l2.extend(l[6:])
>>> l2
['0', '1', '2345', '6', '7', '8', '9']

Is there a way (which I am missing) to make it easier and in place in the original list l?

Edit

As usual, Sven Marnach had a beautiful instant answer:

l[2:6] = ["".join(l[2:6])]

I tried:

l[2:6] = "".join(l[2:6])

But without braces, the string created by the join was then treated as iterability, putting each character on the list and changing the direction of the join!

Consider:

>>> l=['abc','def','ghk','lmn','opq']
>>> l[1:3]=[''.join(l[1:3])] 
>>> l
['abc', 'defghk', 'lmn', 'opq']   #correct

>>> l=['abc','def','ghk','lmn','opq']
>>> l[1:3]=''.join(l[1:3])
>>> l
['abc', 'd', 'e', 'f', 'g', 'h', 'k', 'lmn', 'opq']   #not correct
+5
source share
3 answers

Use the slice assignment:

l[2:6] = ["".join(l[2:6])]
+11

, :

l[2:6] = [''.join(l[2:6])]
+1

:

>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]

EXTENDED :

>>> a=range(6)
>>> a
[0, 1, 2, 3, 4, 5]
>>> a[::2]
[0, 2, 4]
>>> a[::2]=[-1,-2,-3]
>>> a
[-1, 1, -2, 3, -3, 5]
>>> a[::2]=[-1,-2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 2 to extended slice of size 3

If LH is an extended slice, RH should be a sequence of the same length. Regular slice assignment can change the list length to LH.

+1
source

All Articles