Home > Mobile >  Function to remove specific word from lists
Function to remove specific word from lists

Time:07-06

I have several lists that contain the word 'Data' at varying locations in the list. I'd like to build a function that removes just that word (not the whole element) from each list.

example_list = ['Client 1 Data','Client 2','Client 3 Data']

output_list = ['Client 1','Client 2','Client 3']

I've tried this but it is not working:

def my_func(column):
    for i in range(len(column)):
        column.replace('Data', '')

CodePudding user response:

Consider using a list comprehension:

def remove_word(words: list[str], word_to_remove: str) -> list[str]:
    return [w.replace(word_to_remove, '').strip() for w in words]


def main() -> None:
    example_list = ['Client 1 Data', 'Client 2', 'Client 3 Data']
    print(f'{example_list = }')
    output_list = remove_word(words=example_list, word_to_remove='Data')
    print(f'{output_list = }')


if __name__ == '__main__':
    main()

Output:

example_list = ['Client 1 Data', 'Client 2', 'Client 3 Data']
output_list = ['Client 1', 'Client 2', 'Client 3']

CodePudding user response:

you can use map on list but if you want correct your code, you need to specify which index you want to change:

>>> list(map(lambda x: x.replace('Data', ''), example_list))
['Client 1 ', 'Client 2', 'Client 3 ']

Your Code:

def my_func(column):
    for i in range(len(column)):
        column[i] = column[i].replace('Data', '')

Output:

my_func(example_list)
print(example_list)
# ['Client 1 ', 'Client 2', 'Client 3 ']

CodePudding user response:

Calling replace returns a modified string, it doesn't modify the original string. If you want to modify the list, you need to call replace on each individual string and assign the modified strings to the indices in the original list:

>>> def my_func(column):
...     for i in range(len(column)):
...         column[i] = column[i].replace('Data', '')
...
>>> example_list = ['Client 1 Data','Client 2','Client 3 Data']
>>> my_func(example_list)
>>> example_list
['Client 1 ', 'Client 2', 'Client 3 ']

If modifying the original list inside the function isn't a requirement, it's actually easier to do this by building and returning a new list:

>>> def my_func(column):
...     return [entry.replace('Data', '') for entry in column]
...
>>> my_func(['Client 1 Data','Client 2','Client 3 Data'])
['Client 1 ', 'Client 2', 'Client 3 ']

Another option is to build the new list inside the function (e.g. via comprehension) and then assign it into the original list via a slice assignment:

>>> def my_func(column):
...     column[:] = [entry.replace('Data', '') for entry in column]
...
>>> example_list = ['Client 1 Data','Client 2','Client 3 Data']
>>> my_func(example_list)
>>> example_list
['Client 1 ', 'Client 2', 'Client 3 ']
  • Related