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']
>>> l=['abc','def','ghk','lmn','opq']
>>> l[1:3]=''.join(l[1:3])
>>> l
['abc', 'd', 'e', 'f', 'g', 'h', 'k', 'lmn', 'opq']