Say I have a list like this:
[a, b, c, d, e, f, g]
How do modify that list so that it looks like this?
[a, b, c, def, g]
I would much prefer that it modified the existing list directly, not created a new list.
Say I have a list like this:
[a, b, c, d, e, f, g]
How do modify that list so that it looks like this?
[a, b, c, def, g]
I would much prefer that it modified the existing list directly, not created a new list.
That example is pretty vague, but maybe something like this?
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]
It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)
For any type of list, you could do this (using the +
operator on all items no matter what their type is):
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]
This makes use of the reduce
function with a lambda
function that basically adds the items together using the +
operator.
On what basis should the merging take place? Your question is rather vague. Also, I assume a, b, ..., f are supposed to be strings, that is, 'a', 'b', ..., 'f'.
>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> x[3:6] = [''.join(x[3:6])]
>>> x
['a', 'b', 'c', 'def', 'g']
Check out the documentation on sequence types, specifically on mutable sequence types. And perhaps also on string methods.
my telepathic abilities are not particularly great, but here is what I think you want:
def merge(list_of_strings, indices):
list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
return list_of_strings
I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.
just a variation
alist=["a", "b", "c", "d", "e", 0, "g"]
alist[3:6] = [''.join(map(str,alist[3:6]))]
print alist