Assume that I have a list:
l = ['foo', 'bar', 'baz']
How to append pre to bar to have:
l = ['foo', 'prebar', 'baz']
?
Lists are mutable; strings are not. Therefore, assuming you know the index of the string you want to change:
l = ['foo', 'bar', 'baz']
i = 1
l[i] = 'pre' + l[i]
This gives l = ['foo', 'prebar', 'baz'].
Using a list comprehension constructs a whole new list in memory, which is wasteful of resources (though immaterial for small lists). This method modifies the existing list in place.
list.index() is for!You can use + operand to concatenate strings together.So you can use a list comprehension to loop over your list and change the item that is equal with 'bar' :
>>> l1=['pre'+i if i=='bar' else i for i in l1]
>>> l1
['foo', 'prebar', 'baz']