Replace String in List of List

As I learn Python I’m struggling in writing a loop to replace string in a list of list. Please see the following MWE,

list=[['a','alpha'],['b','bravo'],['c','charlie'],['d','delta']]

for entry in list:
    name = entry[1]
    
    if name == 'alpha':
        name = name.replace('alpha','zulu')    
    
    if name == 'bravo':
        name = name.replace('bravo','zulu')   
    
    else:
        name = 'xxx'
    
    entry[1] = name

print(list)

I recognize that the issue is my loop is simply replacing the value with each iteration and therefore not yielding my desired output:
[['a', 'zulu'], ['b', 'zulu'], ['c', 'xxx'], ['d', 'xxx']]. Is there a way of editing my loop so achieve the desired result? Beyond the MWE, I’m working with a fairly large dataset and else command is quite useful.

Thank you!

>Solution :

You can simply use assignment a la name = 'whatever' rather than using replace

Likewise, you can combine the check for alpha and bravo since the replacement value is identical:

entries = [['a','alpha'],['b','bravo'],['c','charlie'],['d','delta']]

for entry in entries:
    name = entry[1]
    if name == 'alpha' or name == 'bravo':
        name = 'zulu'
    else:
        name = 'xxx'
    
    entry[1] = name  # update the list item

print(list)
# => [['a', 'zulu'], ['b', 'zulu'], ['c', 'xxx'], ['d', 'xxx']]

And as @Barmar mentioned, list is a reserved word in Python, so I’ve renamed your list to entries

Leave a Reply