Search code examples
pythonlist-comprehensionenumerate

Find and replace string values in list while looping


I have a List that contains names of items (item01,item02 etc) i Would like to remove some of the old items and add new items in a list

i tried this code:

add_items = 'item22,item23'.split(',')
rmv_items = 'item01,item02'.split(',')
cur_kit_compon = ['item01', 'item02', 'item03', 'item4', 'item5']

for index, x in enumerate(add_items):
    new_kit_compon = [y.replace(rmv_items[index], x) for y in cur_kit_compon]

print('-------------------------')
print(new_kit_compon)

Code output:

['item01', 'item23', 'item03', 'item4', 'item5']

The problem: The code is only removing and adding 1 item instead of 2 items

Desired Output:

['item22', 'item23', 'item03', 'item4', 'item5']

Thank you for all your help


Solution

  • You can build a dictionary mapping the items to remove to their replacements, then use that dictionary to find the replacements for items in your list.

    add_items = 'item22,item23'.split(',')
    rmv_items = 'item01,item02'.split(',')
    
    replacements = dict(zip(rmv_items, add_items))
    
    cur_kit_compon = ['item01', 'item02', 'item03', 'item4', 'item5']
    res = [replacements.get(item, item) for item in cur_kit_compon]
    # ['item22', 'item23', 'item03', 'item4', 'item5']