Perform a string operation for every element in a Python list

Question:

I have a list of strings in Python – elements. I would like to edit each element in elements. See the code below (it doesn’t work, but you’ll get the idea):

for element in elements:
    element = "%" + element + "%"

Is there a way to do this?

Asked By: locoboy

||

Answers:

You can use list comprehension:

elements = ["%" + e + "%" for e in elements]
Answered By: Achim

You can use list comprehensions:

elements = ["%{}%".format(element) for element in elements]
Answered By: leoluk
elements = ['%{0}%'.format(element) for element in elements]
Answered By: JBernardo
elements = map(lambda e : "%" + e + "%", elements)
Answered By: bpgergo

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.

Answered By: steveha

Here some more examples

char = [‘g:’, ‘l:’, ‘q:’]

Using Replace

for i in range(len(char)):
    char[i] = char[i].replace(':', '')

Using strip

for i in range(len(char)):
    char[i] = char[i].strip(':')

Using a function

def list_cleaner(list_):
    return [char_.strip(':') for char_ in list_]


new_char = list_cleaner(char)
print(new_char)

Using Generator function(adviced if you have a large piece of data)

def generator_cleaner(list_):
    yield from (char_.strip(':') for char_ in list_)

# Prints all results in once
gen_char = list(generator_cleaner(char))

# Prints as much as you need, in this case only 8 chars
# I increase a bit the list so it makes more sense
char = ['g:', 'l:', 'q:', 'g:', 'l:', 'q:', 'g:', 'l:', 'q:']

# let's call our Generator Function
gen_char_ = generator_cleaner(char)

# We call only 8 chars
gen_char_ = [next(gen_char_) for _ in range(8)]
print(gen_char_)
Answered By: Federico Baù

Python 3.6+ version (f-strings):

elements = [f'%{e}%' for e in elements]
Answered By: ZygD