Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading