Perform a string operation for every element in a Python list

Solution 1:

elements = ['%{0}%'.format(element) for element in elements]

Solution 2:

You can use list comprehension:

elements = ["%" + e + "%" for e in elements]

Solution 3:

You can use list comprehensions:

elements = ["%{}%".format(element) for element in elements]

Solution 4:

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.

Solution 5:

Python 3.6+ version (f-strings):

elements = [f'%{e}%' for e in elements]