I have an list of string elements in python elements
and would like edit each element in elements with so I have a new element. See code below (it doesn\'t work
You can use list comprehension:
elements = ["%" + e + "%" for e in elements]
elements = ['%{0}%'.format(element) for element in elements]
You can use list comprehensions:
elements = ["%{}%".format(element) for element in elements]
There are basically two ways you can do what you want: either edit the list you have, or else create a new list that has the changes you want. All the answers currently up there show how to use a list comprehension (or a map()
) to build the new list, and I agree that is probably the way to go.
The other possible way would be to iterate over the list and edit it in place. You might do this if the list were big and you only needed to change a few.
for i, e in enumerate(elements):
if want_to_change_this_element(e):
elements[i] = "%{}%".format(e)
But as I said, I recommend you use one of the list comprehension answers.
elements = map(lambda e : "%" + e + "%", elements)