Suppose I have a simple Python list like this:
>>> l=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Now suppose I want to combine l[2:6] to a single element like this:
>>> l
['0', '1', '2345', '6', '7', '8', '9']
I am able to do it in steps into a new list, like this:
>>> 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 (that I am missing) to do this more simply and in place on the original list l?
Edit
As usual, Sven Marnach had the perfect instant answer:
l[2:6] = ["".join(l[2:6])]
I had tried:
l[2:6] = "".join(l[2:6])
But without the braces, the string produced by the join was then treated as an iterable placing each character back in the list and reversing 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
Use a slice assignment: